[阅读: 447] 2004-12-02 03:19:35
好像不能用在c++里面用...
Static Constructors
This is a new concept introduced in C#. By new here, I mean that it was not available for the C++ developers. This is a special constructor and gets called before the first object is created of the class. The time of execution cannot be determined, but it is definitely before the first object creation - could be at the time of loading the assembly.
The syntax of writing the static constructors is also damn simple. Here it is:
public class myClass
{
static myClass()
{
// Initialization code goes here.
// Can only access static members here.
}
// Other class methods goes here
}
Notes for Static Constructors:
There can be only one static constructor in the class.
The static constructor should be without parameters.
It can only access the static members of the class.
There should be no access modifier in static constructor definition.
Ok fine, all the above points are fine, but why is it like that? Let us go step by step here.
Firstly, the call to the static method is made by the CLR and not by the object, so we do not need to have the access modifier to it.
Secondly, it is going to be called by CLR, who can pass the parameters to it, if required. So we cannot have parameterized static constructor.
Thirdly, non-static members in the class are specific to the object instance. So static constructor, if allowed to work on non-static members, will reflect the changes in all the object instances, which is impractical. So static constructor can access only static members of the class.
Fourthly, overloading needs the two methods to be different in terms of methods definition, which you cannot do with Static Constructors, so you can have at the most one static constructor in the class.
Now, one question raises here, can we have two constructors as:
public class myClass
{
static myClass()
{
// Initialization code goes here.
// Can only access static members here.
}
public myClass()
{
// Code for the First myDerivedClass Constructor.
}
// Other class methods goes here
}
This is perfectly valid, though doesn’t seem to be in accordance with overloading concepts. But why? Because the time of execution of the two methods are different. One is at the time of loading the assembly and one is at the time of object creation.