zoukankan      html  css  js  c++  java
  • 编写高质量代码改善C#程序的157个建议——建议33:避免在泛型类型中声明静态成员

    建议33:避免在泛型类型中声明静态成员

    在上一建议中,已经理解了应该将MyList<int>和MyList<string>视作两个完全不同的类型,所以,不应该将MyList<T>中的静态成员理解成MyList<int>和MyList<string>共有的成员。

        class MyList
        {
            public static int Count { get; set; }
            public MyList()
            {
                Count++;
            }
        }
    
        static void Main(string[] args)
        {
            MyList list1=new MyList();
            MyList list2=new MyList();
            Console.WriteLine(MyList.Count);
        }

    输入:

    2

    若果换成泛型:

        class MyList<T>
        {
            public static int Count { get; set; }
            public MyList()
            {
                Count++;
            }
        }
    
        static void Main(string[] args)
        {
            MyList<int> list1 = new MyList<int>();
            MyList<int> list2 = new MyList<int>();
            MyList<string> list3=new MyList<string>();
            Console.WriteLine(MyList<int>.Count);
            Console.WriteLine(MyList<string>.Count);
        }

    输出为:

    2

    1

    实际上,随着你为T指定不同的数据类型,MyList<T>相应地也变成不同的数据类型,它们之间是不共享静态成员的。

    若T所指定的数据类型一致,那么两个泛型对象之间还是可以共享静态成员的,如上文中的list1和list2。但是为了避免因此引起的混淆,仍旧建议在实际编码过程中,尽量避免声明泛型类型的静态成员。

    非泛型类型中静态泛型方法看起来很接近该例子,但是,非泛型中的泛型方法并不会在运行时的本地代码中生成不同的类型。

    如下:

            class MyList
            {
                static int count;
                public static int Func<T>()
                {
                    return count++;
                }
            }
    
            static void Main(string[] args)
            {
                Console.WriteLine(MyList.Func<int>());
                Console.WriteLine(MyList.Func<int>());
                Console.WriteLine(MyList.Func<string>());
            }

    输出:

    0

    1

    2

    转自:《编写高质量代码改善C#程序的157个建议》陆敏技

  • 相关阅读:
    Hello & Goodbye
    如何将 SQL SERVER 彻底卸载干净
    C#中Split用法
    Tensorflow2(预课程)---7.4、cifar10分类-层方式-卷积神经网络-AlexNet8
    Tensorflow2(预课程)---5.3.2、手写数字识别-层方式-卷积神经网络-LeNet-5稍改
    Tensorflow2(预课程)---5.3、手写数字识别-层方式-卷积神经网络-LeNet
    LeNet-5详解
    卷积神经网络-LeNet
    LeNet结构详细分析
    降采样层和池化层的关系
  • 原文地址:https://www.cnblogs.com/jesselzj/p/4732040.html
Copyright © 2011-2022 走看看