标签:
老赵写的文章,原文:http://blog.zhaojie.me/2009/09/i-made-a-mistake-can-you-figure-it-out-answer.html
public static class MyClass<T> { public static readonly Guid Key = Guid.NewGuid(); } class Program { static void Main(string[] args) { Console.WriteLine("int: " + MyClass<int>.Key); Console.WriteLine("string: " + MyClass<string>.Key); Console.ReadLine(); } }
上面结果是不一样的。。。。。
在泛型类中定义静态字段的时候一定要注意:不同泛型参数生成的具体类(无论是值类型还是引用类型),它们的静态字段是独立的。
public class StaticTest { public static void Test() { Console.WriteLine("int:" + MyClass<int>.key); Console.WriteLine("string:" + MyClass<string>.key); } public static void Test2() { Console.WriteLine("int:" + MyClass2<int>.time); System.Threading.Thread.Sleep(3000); Console.WriteLine("string:" + MyClass2<string>.time); } public static void Test3() { Console.WriteLine("Test3 execute!"); Console.WriteLine("int:" + MyClass3<int>.time); System.Threading.Thread.Sleep(3000); Console.WriteLine("string:" + MyClass3<string>.time); } } /// <summary> /// 不同泛型参数生成的具体类(无论是值类型还是引用类型),它们的静态字段是独立的 /// </summary> /// <typeparam name="T"></typeparam> static class MyClass<T> { public static readonly Guid key = Guid.NewGuid(); } static class MyClass2<T> { public static readonly DateTime time = DateTime.Now; } /// <summary> /// 增加一个空的静态构造函数 /// </summary> /// <typeparam name="T"></typeparam> static class MyClass3<T> { public static readonly DateTime time = GetNow(); private static DateTime GetNow() { Console.WriteLine("GetNow execute!"); return DateTime.Now; } static MyClass3() { } }
转老赵--不同泛型参数生成的具体类(无论是值类型还是引用类型),它们的静态字段是独立的
标签:
原文地址:http://www.cnblogs.com/ly7454/p/4588503.html