c# - .Net 中的私有(private)构造函数与静态构造函数

标签 c# .net static-constructor private-constructor

我搜索了很多次,但没有一个答案是明确的(至少对我来说是这样!)。现在我把这个问题放在 SO 中,因为我相信我无法在其他任何地方得到更明确的答案。

什么时候应该在我的类中使用私有(private)/静态构造函数?

我受够了通常的答案,所以请帮助我提供一些实时示例以及使用这些构造函数的优点/缺点。

最佳答案

静态构造函数:用于初始化静态成员。

私有(private)构造函数:当您只希望一个类在其自己的代码中实例化时使用(通常在静态方法中)。例如:

public class Thing
{
    static int Number;

    static Thing()
    {
        Number = 42; // This will only be called once, no matter how many instances of the class are created
    }

    // This method is the only means for external code to get a new Thing
    public static Thing GetNewThing()
    {
        return new Thing();
    }

    // This constructor can only be called from within the class.
    private Thing()
    {
    }
}

关于c# - .Net 中的私有(private)构造函数与静态构造函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13248320/

相关文章:

.net - OracleCommand 内存泄漏

c# - 从对象创建 Xml 文件

c# - 如何在 C# 中的运行时实现带参数的静态字典<T>?

c# - 将参数传递给单例类/静态构造函数

c# - 我可以修改 Win7 环境以允许 .Net 程序始终以管理员身份运行吗?

c# - 数据绑定(bind)和重构代码

c# - 仅从字符串中获取测量值

.Net POP3 客户端

c# - Assembly.GetCallingAssembly() 和静态构造函数?

c# - 是否有用于查询 C# 文件的 LINQ 查询提供程序?