读书人

求详解一段示范代码中的技术点

发布时间: 2013-08-01 15:23:18 作者: rapoo

求详解一段示例代码中的技术点
一个泛型单例基类。


using System;
using System.Linq;
using System.Reflection;

namespace SingletonDemo
{
public abstract class Singleton
{
private static readonly Lazy<T> _instance
= new Lazy<T>(() =>
{
var ctors = typeof(T).GetConstructors(
BindingFlags.Instance
|BindingFlags.NonPublic
|BindingFlags.Public);
if (ctors.Count() != 1)
throw new InvalidOperationException(String.Format("Type {0} must have exactly one constructor.",typeof(T)));
var ctor = ctors.SingleOrDefault(c => c.GetParameters().Count() == 0 && c.IsPrivate);
if (ctor == null)
throw new InvalidOperationException(String.Format("The constructor for {0} must be private and take no parameters.",typeof(T)));
return (T)ctor.Invoke(null);
});

public static T Instance
{
get { return _instance.Value; }
}
}
}

点链接可以看到原地址,点不开的话多刷几遍就可以。
http://www.fascinatedwithsoftware.com/blog/post/2011/07/13/A-Generic-Singleton-Class.aspx

求深入详解,蜻蜓点水的就不要啦。
[解决办法]
象下面的写法,是不是更容易理解一些?



public abstract class Singleton<T> where T : new()
{
private static Lazy<T> _instance = new Lazy<T>(() => new T());
public static T Instance
{
get { return _instance.Value; }
}
}
// 甚至这样写都可以:
public abstract class Singleton2<T> where T : new()
{
private static T _instance = new T();
public static T Instance
{
get { return _instance; }
}
}


[解决办法]
Lazy<T>:
Use lazy initialization to defer the creation of a large or resource-intensive object, or the execution of a resource-intensive task, particularly when such creation or execution might not occur during the lifetime of the program.

To prepare for lazy initialization, you create an instance of Lazy<T>. The type argument of the Lazy<T> object that you create specifies the type of the object that you want to initialize lazily. The constructor that you use to create the Lazy<T> object determines the characteristics of the initialization. Lazy initialization occurs the first time the Lazy<T>.Value property is accessed.
以上来自msdn:
http://msdn.microsoft.com/en-us/library/dd642331(v=vs.100).aspx
[解决办法]
知识点,泛型、反射(构造函数)、Lambda表达式、.NET 4.0库中的Lazy<T>、延迟加载的单键设计模式、抽象类和泛型。

读书人网 >C#

热点推荐