问题
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.
回答1:
Static constructors: used for initialising static members.
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()
{
}
}
回答2:
When should I use a private constructor in my class?
When you want a constructor, but don't want to expose it to the world. This could be because you have a factory method that calls the constructor (after validation), or because that constructor is called by ctor-chaining (i.e. public Foo(string) : this() { ...}
).
Additionally, note that reflection code is often able to use a private constructor - for example serialization or ORM libraries.
Also, in early C# compilers, when you are writing what would now be a static
class - having a private constructor was the only way of making it appear uncreatable.
When should I use a static constructor in my class?
When you need to initialize some static state prior to that state being accessed by instances or static methods.
回答3:
Static constructor is used to intialize the static members of the class and is called when the first instance of the class is created or a static member is accessed for the first time.
Private constructor is used if you have overloads of the constructor, and some of them should only be used by the other constructors
来源:https://stackoverflow.com/questions/13248320/private-vs-static-constructors-in-net