【发布时间】:2013-08-10 04:08:32
【问题描述】:
我已经根据this page 使用System.Lazy<T> 实现了单例。
我想知道,当构造函数的访问修饰符是private 时,System.Lazy<T> 在技术上如何访问T 的构造函数。
【问题讨论】:
标签: c#-4.0 constructor singleton access-modifiers lazy-initialization
我已经根据this page 使用System.Lazy<T> 实现了单例。
我想知道,当构造函数的访问修饰符是private 时,System.Lazy<T> 在技术上如何访问T 的构造函数。
【问题讨论】:
标签: c#-4.0 constructor singleton access-modifiers lazy-initialization
Lazy<T> 使用匿名方法实例化如下:
new Lazy<Singleton>(() => new Singleton());
匿名方法只是位于定义它们的类中的私有方法。由于这是类中的一个方法,因此允许访问该类的任何其他私有成员,包括私有构造函数。
C# 编译器生成的代码与以下代码非常相似:
Func<Singleton> factory = this.__compiler_generated_method;
new Lazy<Singleton>(factory);
private static Singleton __compiler_generated_method()
{
return new Singleton();
}
【讨论】:
Lazy<T> 的构造函数