为什么我们需要一个私人的构造?私人

2023-09-02 20:45:27 作者:最终不相认

如果一个类有一个私有的构造函数,然后它不能被实例化。 所以,如果我不希望我的类实例化和仍然使用它,那么我可以让静态的。

If a class has a private constructor then it can't be instantiated. So, if I don't want my class to be instantiated and still use it, then I can make it static.

什么是使用私有构造的?

What is the use of a private constructor?

另外它采用单例类,但不同的是,还有没有其他用途?

Also it's used in singleton class, but except for that, is there any other use?

(注:我不包括单身上述情况的原因是因为我不明白为什么我们需要一个单身在所有的时候有一个静态类可用您可能不能回答这个我在这个问题困惑。)

(Note: The reason I am excluding the singleton case above is because I don't understand why we need a singleton at all when there is a static class available. You may not answer this for my confusion in the question. )

推荐答案

工厂

私有构造函数可以使用时,工厂模式(换句话说,这是用于获取类的实例,而不是显式实例化一个静态函数)是有用的。

Private constructors can be useful when using a factory pattern (in other words, a static function that's used to obtain an instance of the class rather than explicit instantiation).

public class MyClass
{ 
    private static Dictionary<object, MyClass> cache = 
        new Dictionary<object, MyClass();

    private MyClass() { }

    public static MyClass GetInstance(object data)
    {
        MyClass output;

        if(!cache.TryGetValue(data, out output)) 
            cache.Add(data, output = new MyClass());

        return output;           
    }
}

伪密封带嵌套子

这是从外部类继承任何嵌套类可以访问私有的构造。

Any nested classes that inherit from the outer class can access the private constructor.

例如,你可以使用它来创建的一个抽象类,你的可以继承,但没有其他人(的内部构造函数同时在这里工作,限制继承到一个单一的组件,但私人构造力量所有的实现被嵌套类。)

For instance, you can use this to create an abstract class that you can inherit from, but no one else (an internal constructor would also work here to restrict inheritance to a single assembly, but the private constructor forces all implementations to be nested classes.)

public abstract class BaseClass
{
    private BaseClass() { }

    public class SubClass1 : BaseClass
    {
        public SubClass1() : base() { }
    }

    public class SubClass2 : BaseClass
    {
        public SubClass2() : base() { }
    }
}

基本构造

它们也可以用于创建基构造方法,它是从不同的,更方便的构造调用。

They can also be used to create "base" constructors that are called from different, more accessible constructors.

public class MyClass
{
    private MyClass(object data1, string data2) { }

    public MyClass(object data1) : this(data1, null) { }

    public MyClass(string data2) : this(null, data2) { }

    public MyClass() : this(null, null) { }
}