I've implemented singleton according to this page using System.Lazy<T>.

I wonder, how technically can System.Lazy<T> access constructor of T, when access modificator of constructor is private.

有帮助吗?

解决方案

The Lazy<T> is instantiated with an anonymous method as follows:

new Lazy<Singleton>(() => new Singleton());

Anonymous methods are under the covers just private methods located in the class that defines them. Since this is a method in the class, it is allowed to access any other private members of that class including the private constructor.

The code the C# compiler generates closely resembles the following:

Func<Singleton> factory = this.__compiler_generated_method;
new Lazy<Singleton>(factory);

private static Singleton __compiler_generated_method()
{
    return new Singleton();
}
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top