问题
I am reading a code in C# that uses two constructors. One is static and the other is public. What is the difference between these two constructors? And for what we have to use static constructors?
回答1:
static
and public
are orthogonal concepts (i.e. they don’t have anything to do with each other).
public
simply means that users of the class can call that constructor (as opposed to, say, private
).
static
means that the method (in this case the constructor) belongs not to an instance of a class but to the “class itself”. In particular, a static constructor is called once, automatically, when the class is used for the first time.
Furthermore, a static constructor cannot be made public
or private
since it cannot be called manually; it’s only called by the .NET runtime itself – so marking it as public
wouldn’t be meaningful.
回答2:
Static constructor runs just once, before your class is instantiated. It's used if you want something to happen just once. A nice example would be a Bus class (similar to something they explain in MSDN article):
public class Bus
{
public static int busNo = 0;
static Bus()
{
Console.WriteLine("Woey, it's a new day! Drivers are starting to work.");
}
public Bus()
{
busNo++;
Console.WriteLine("Bus #{0} goes from the depot.", busNo);
}
}
class Program
{
static void Main(string[] args)
{
Bus busOne = new Bus();
Bus busTwo = new Bus();
}
// Output:
// Woey, it's a new day! Drivers are starting to work.
// Bus #1 goes from the depot.
// Bus #2 goes from the depot.
}
回答3:
Static Constructor... It is guaranteed to be called "once" througout the life of the application/app Domain. It can contain statements that you want to be executed only once.
Public Constructor... Since we can not add access modifiers to a static constructor, a public constructor means you are talking about an instance constructor. If an instance constructor is public then the outside world can create its instances. Other options are Internal ( can be called from within the library), Private ( from within the class only).
回答4:
Static Constructor
A constructor declared using static modifier is a static constructor. A static constructor is use to initialize static data or to perform a particular action that need to be performed only once in life cycle of class. Static constructor is first block of code to execute in class. Static constructor executes one and only one time in life cycle of class. It is called automatically. Static constructor does not take any parameters. It has no access specifiers. It is not called directly.
Instance or Public Constructor
Instance constructor is used to initialize instance data. Instance constructor is called every time when object of class is created. It is called explicitly. Instance constructor takes parameters. It has access specifiers.
来源:https://stackoverflow.com/questions/2995448/public-constructor-and-static-constructor