观《深入理解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行不输出,因为跟第一行一样,已经生成过了

posted @ 2024-07-11 14:32  陈侠云  阅读(54)  评论(0)    收藏  举报
//雪花飘落效果