Preface:
Starting with C ++, constructor started to access. But a few days ago, I saw the static constructor problem in C #, but I still feel a little unfamiliar. Let's take a look.
Resolution:
First lookCodeTo demonstrate the usage of constructor:
// Description: describes the relationship between static constructors.
//Copyright:Http://www.cnblogs.com/yangmingming
// Notes: demo with a specific instance
Public Class A
{
Public Static Int A;
Static A ()
{
A ++ ;
}
Public A ()
{
A ++ ;
}
}
Class Program
{
Static Void Main ( String [] ARGs)
{
A = New A ();
A A2 = New A ();
Console. writeline ( " The value of static A is {0} " , A. );
}
}
The debugging result is:
Why? There must be problems in the middle, or there is no clear law. The original problem was thatStatic Constructor.
Resolution:
Original static constructor,Only once when the class is loadedEven if multiple objects are instantiated, they can be executed at most once, and executed before the instantiated object or class uses the members. See the following code: (slightly modify the above Code)
// Description: describes the relationship between static constructors.
//Copyright:Http://www.cnblogs.com/yangmingming
// Notes: demo with a specific instance
Public Class A
{
Static A ()
{
Console. writeline ( " Static " );
}
Public A ()
{
Console. writeline ( " Public " );
}
}
Class Program
{
Static Void Main ( String [] ARGs)
{
A = New A ();
A A2 = New A ();
}
}
The result is:
That is, the above explanation is verified. However, for static constructor, there are several points to note, see:
Appendix:
- Static constructor,Yes No Parameter FunctionAnd a class can only have one static constructor, because the static constructor can only access static members of the class, but cannot access instance members;
- Static constructor,No access modifierBecause C # Never calls it, that is, adding private or public makes no sense;
In summary, through the application of the static constructor, We have deepened our understanding of this special constructor and also understood its functions. Haha ~