Static members belong to Classes rather than instances. Static members have a wide range of applications. For example, public static member values can be obtained or set globally in an application, which is similar to the global variables of C ++, however, improper use may also cause problems.
Class Test
{
Private Static string strstaticname = "hello ";
// No parameter Constructor
Public test ()
{
}
// Parameter Constructor
Public test (string strname)
{
Strstaticname = strname;
}
Public String getname ()
{
Return strstaticname;
}
}
Static void main (string [] ARGs)
{
Console. writeline ("when you create a T1 instance, set the name to Oriental ");
// Create instance T1
Test T1 = new test ("oriental ");
Console. writeline ("so the name obtained using the getname method is: {0}", t1.getname ());
Console. writeline ("");
// Create instance T2
Console. writeline ("when creating T2 instance, the name is not set ");
Test t2 = new test ();
String strname = t2.getname ();
Console. writeline ("but the name obtained through the getname method is: {0}", strname );
Console. Read ();
}
After debugging:
Analysis: in an application, no matter how many instances of a class are created, the static fields of the class are initialized only once.
Solution: 1) Cancel static keyword static
2) All constructors with parameters are used.
3) assign values to static fields in the no-argument Constructor
Public test ()
{
Strstaticname = "hello ";
}
Blind Zone generated when initializing static members