【问题标题】:How can System.Lazy<T> access private constructor of T?System.Lazy<T> 如何访问 T 的私有构造函数?
【发布时间】:2013-08-10 04:08:32
【问题描述】:

我已经根据this page 使用System.Lazy&lt;T&gt; 实现了单例。

我想知道,当构造函数的访问修饰符是private 时,System.Lazy&lt;T&gt; 在技术上如何访问T 的构造函数。

【问题讨论】:

    标签: c#-4.0 constructor singleton access-modifiers lazy-initialization


    【解决方案1】:

    Lazy&lt;T&gt; 使用匿名方法实例化如下:

    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();
    }
    

    【讨论】:

    • 我明白了,因此需要将 T 的构造函数作为匿名方法传递给 Lazy&lt;T&gt; 的构造函数
    猜你喜欢
    • 2013-05-02
    • 1970-01-01
    • 1970-01-01
    • 2021-04-17
    • 1970-01-01
    • 2011-02-05
    • 2011-05-17
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多