我已经根据这个页面使用System.Lazy<T>
实现了singleton。
我想知道,当构造函数的访问修饰符是private
时,System.Lazy<T>
在技术上如何访问T
的构造函数。
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();
}