C # generics-use static member variables with caution

Source: Internet
Author: User

For the declaration of a generic class
which uses the type parameter's constructed type, such as list<t>, which is called an open constructed type (open constructed type)
A constructed type that does not use a type parameter, such as List<int>, is called a closed constructed type (closed constructed type).
It is particularly emphasized that static member variables are not shared between closed constructed types with different types of parameters.

As an example,

Using System;

public class List<t>
{
Public List (T t)
{
_value = t;
_closedcount++;
}

Public T Value
{
get {return _value;}
}

public int Closedcount
{
get {return _closedcount;}
}

public static int Staticcount
{
get {return _closedcount;}
}


Private T _value;
private static int _closedcount = 0;
}

public class Test
{
static void Main ()
{
List<double> List1 = new list<double> (3.14);
Console.WriteLine ("List1 Value: {0} \ t Closed Count: {1}", List1. Value, List1. Closedcount);

list<double> list2 = new list<double> (0.618);
Console.WriteLine ("List2 Value: {0} \ t Closed Count: {1}", List2. Value, List2. Closedcount);

list<string> list3 = new List<string> ("Divino");
Console.WriteLine ("List3 Value: {0} \ t Closed Count: {1}", List3. Value, List3. Closedcount);

Console.WriteLine ();

Console.WriteLine ("list<double> Count: {0}", List<double>. Staticcount);
Console.WriteLine ("list<string> Count: {0}", List<string>. Staticcount);
}
}

Output Result:
List1 value:3.14 Closed count:1
List2 value:0.618 Closed Count:2
List3 Value:divino Closed count:1

List<double> Count:2
List<string> count:1

which
List1 and List2 are list<double> they share static members _closedcount
List3 of type list<string> cannot be used _closedcount
We can also see the results from the last two lines of output
That is, static member variables are not shared between closed constructed types of different types of parameters.

C # generics-use static member variables with caution

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.