本文介绍了在净私人VS静态构造函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我搜索了这个有很多,但没有一个答案是明确的(AT-至少对我来说!)。现在,我把这个问题的SO,我相信我能不能得到一个更明确的答案其他地方。

I searched for this a lot, but none of the answers are clear (at-least for me!). Now I'm putting this question in SO, as I believe I can't get a more clarified answer anywhere else.

当我应该使用私有/静态构造函数在我的课?

When should I use a private/static constructor in my class?

我受够了通常的答案,所以请帮助我,用这些构造的一些实时的例子和优势/劣势。

I'm fed up of usual answers, so please help me with some real-time examples and advantages/disadvantages of using these constructors.

推荐答案

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

Static constructors: used for initialising static members.

私有构造函数:使用时,您只需要一个类从在自己的code(通常以一个静态方法)实例化。例如:

Private constructors: used when you only want a class to be instantiated from within its own code (typically in a static method). For example:

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

这篇关于在净私人VS静态构造函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-29 16:07