zoukankan      html  css  js  c++  java
  • 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} Closed Count: {1}", list1.Value, list1.ClosedCount);

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

            List<string> list3 = new List<string>("divino");
            Console.WriteLine("List3 Value: {0} 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
    我们从最后两行的输出也可看出结果
    即:不同类型参数的封闭构造类型之间是不共享静态成员变量的。

  • 相关阅读:
    PythonStudy——epoll 模块实现异步IO模型
    MySQLStudy——Mac下MySQL 允许用户远程访问数据库
    MySQLStudy——MySQL 基础语句
    MySQLStudy——MySQL 概念
    MySQLStudy——Mac下MySQL 常用命令 启动 关闭 重启服务 查看版本
    PythonStudy——IO模型
    PythonStudy——非阻塞IO模型
    PythonStudy——多路复用IO select实现
    restfull api
    斜体菜单
  • 原文地址:https://www.cnblogs.com/fujinliang/p/4395009.html
Copyright © 2011-2022 走看看