A variable or function declared with static, belong to the class, not to the class object, so it is best not to initialize the static variable in the constructor of the class (no need to initialize it, because C # defaults to the static variable first, such as STAITC integer variables, is initialized to 0). If you initialize a static variable in the constructor of a class, the initialization of the static variable works only after you have new the object of that class.
One, for example: The following code defines a Static_test class that has a static type list variable and initializes it in the constructor.
Class Static_test { //define static variables
public static list<int> M_lst; public static_test () { //initialization of M_LST in constructors
m_lst = new list<int> (); for (int i = 0; i < ++i) & nbsp; { M_lst.
ADD (i);
} } ///<summary> ///printing m_ LST &NBSP;&NBSP;&NBSP;&NBSP;&NBsp; ///</summary> public static void Printlist () & nbsp; { if (m_lst = = null) {
Console.WriteLine ("List is null");
return; } for (int i = 0; i < M_lst. Count; ++i) {
Console.Write (M_lst[i] + ""); } &NBSP;&NBSP;&NBSP;&NBSP;&NBsp; Console.WriteLine (); } }
1. At this point, the static_test is called directly when an object of the Static_test type has not been defined. Printlist (), as follows:
static void Main (string[] args)
{
static_test. Printlist ();
Console.readkey ();
}
Output:
The list is null
2. If you have defined an object of type Static_test, then call Static_test. Printlist (), M_lst will have a value.
static void Main (string[] args)
{
static_test test = new Static_test ();
Static_test. Printlist ();
Console.readkey ();
}
Output:
0 1 2 3 4 5 6 7 8 9
Second, my personal point of view, will need to initialize the static variables, declared in the class, is initialized to avoid unnecessary errors. as follows, a initlist () static member function is added, which is initialized by the static member variable at declaration time.
Class Static_test
{
//define static variable public
static list<int> m_lst = Initlist ();
Public Static_test ()
{
}
private static list<int> initlist ()
{
list<int> lst = new List<int> ();
for (int i = 0; i < ++i)
{
lst. ADD (i);
}
return lst;
}
<summary>
///Print m_lst
///</summary> public
static void Printlist ()
{
if (m_ LST = = null)
{
Console.WriteLine ("List is null");
return;
}
for (int i = 0; i < M_lst. Count; ++i)
{
Console.Write (M_lst[i] + "");
}
Console.WriteLine ();
}
At this point, the static_test is called directly when an object of the Static_test type has not been defined. Printlist (), as follows:
static void Main (string[] args)
{
static_test. Printlist ();
Console.readkey ();
}
Output:
0 1 2 3 4 5 6 7 8 9