C#泛型-小心使用靜態成員變數

來源:互聯網
上載者:User

標籤:

對於泛型類的聲明
其中使用型別參數的構造類型,比如List<T>被稱為開放構造類型(open constructed type)
而不使用型別參數的構造類型,例如List<int>被稱為封閉構造類型(closed constructed type)。
特別要強調的是不同型別參數的封閉構造類型之間是不共用靜態成員變數的。

舉個例子

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);
    }
}

輸出結果:
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

其中:
list1與list2同為List<double>,它們之間共用靜態成員_closedCount
而類型為List<string>的list3不能使用_closedCount
我們從最後兩行的輸出也可看出結果
即:不同型別參數的封閉構造類型之間是不共用靜態成員變數的。

C#泛型-小心使用靜態成員變數

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

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.