C#泛型-小心使用静态成员变量

对于泛型类的声明
其中使用类型参数的构造类型,比如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
我们从最后两行的输出也可看出结果
即:不同类型参数的封闭构造类型之间是不共享静态成员变量的。

转载于:https://www.cnblogs.com/fujinliang/p/4395009.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值