开头很简单,最难的是坚持。|

陈侠云

园龄:2年10个月粉丝:1关注:1

观《深入理解C#》有感---泛型类中的静态字段

就像实例字段从属于一个实例一样,静态字段从属于声明它们的类型。不管从该类型中创建了多少实例,都有且只有这一个静态字段。
那对于泛型类中的静态字段呢?


答案是:每个封闭类型都有它们自己的静态字段集,例如以下代码:

        public class Blue<T>
        {
            public static string color;
        }

        static void Main(string[] args)
        {
            Blue<int>.color = "int";
            Blue<string>.color = "string";

            Console.WriteLine(Blue<int>.color);
            Console.WriteLine(Blue<string>.color);
        }

最终的输出是:

int
string

同样的规则也适用于静态初始化程序和静态构造函数,例如以下代码:

        public class Outer<T>
        {
            public class Inner<U,V>
            {
                static Inner()
                {
                    Console.WriteLine($"Outer<{typeof(T).Name}>.Inner<{typeof(U).Name},{typeof(V).Name}>");
                }

                public static void DummyMethod() { }
            }
        }

        static void Main(string[] args)
        {
            Outer<int>.Inner<string, float>.DummyMethod();
            Outer<int>.Inner<double, long>.DummyMethod();
            Outer<float>.Inner<string, float>.DummyMethod();
            Outer<int>.Inner<string, float>.DummyMethod();  // 不会输出
        }

最终的输出:

Outer<Int32>.Inner<String,Single>
Outer<Int32>.Inner<Double,Int64>
Outer<Single>.Inner<String,Single>

第4行不输出,因为跟第一行一样,已经生成过了

本文作者:陈侠云

本文链接:https://www.cnblogs.com/chenxiayun/p/18296089

版权声明:本作品采用知识共享署名-非商业性使用-禁止演绎 2.5 中国大陆许可协议进行许可。

posted @   陈侠云  阅读(26)  评论(0编辑  收藏  举报
//雪花飘落效果
点击右上角即可分享
微信分享提示
评论
收藏
关注
推荐
深色
回顶
收起