Recommendation 33: Avoid declaring static members in generic types
In the previous recommendation, it was understood that mylist<int> and mylist<string> should be treated as two completely different types, so that static members in mylist<t> should not be understood as Mylist<int Members of > and mylist<string>.
class MyList { public static int Count {get ; set public MyList () {Count ++ static void Main (string [] args) {MyList list1 =new MyList (); MyList list2 = MyList (); Console.WriteLine (Mylist.count); }
Input:
2
If you change to generic type:
classMylist<t> { Public Static intCount {Get;Set; } PublicMyList () {Count++; } } Static voidMain (string[] args) {MyList<int> List1 =Newmylist<int>(); MyList<int> List2 =Newmylist<int>(); MyList<string> list3=Newmylist<string>(); Console.WriteLine (MyList<int>. Count); Console.WriteLine (MyList<string>. Count); }
The output is:
2
1
In fact, as you specify different data types for T,,mylist<t> also become different data types, and they are not shared by static members.
If the data type specified by T is the same, then the static members can be shared between two generic objects, such as List1 and List2 above. However, to avoid the resulting confusion, it is recommended to avoid declaring static members of generic types as much as possible during the actual coding process.
A static generic method in a non-generic type looks close to the example, but a generic method in a non-generic style does not generate a different type in the local code at run time.
As follows:
classMyList {Static intcount; Public Static intFunc<t>() { returncount++; } } Static voidMain (string[] args) {Console.WriteLine (Mylist.func<int>()); Console.WriteLine (Mylist.func<int>()); Console.WriteLine (Mylist.func<string>()); }
Output:
0
1
2
Turn from: 157 recommendations for writing high-quality code to improve C # programs Minjia
157 recommendations for writing high-quality code to improve C # programs--Recommendation 33: Avoid declaring static members in generic types