静态构造函数(Static Constructor)(It performs well in Singleton)
今天无意间看到了静态构造函数的代码,也许是没怎么见过,觉得新鲜,就顺手写了以下代码,或许我见过,或许我忘记了……呵呵,发布上来自己作个纪念……
发现用来做Singleton模式倒是不错,呵呵……
using System; namespace CA_StaticConstructor { class StaticClass { public static StaticClass Instance { get; set; } public string Name { get; set; } static StaticClass() { if (Instance == null) { Instance = new StaticClass(); } } } class Program { static void Main(string[] args) { StaticClass sc1 = StaticClass.Instance; sc1.Name = "sc1 Instance"; Console.WriteLine(sc1.Name); StaticClass sc2 = StaticClass.Instance; //Without set Name property to Instance Console.WriteLine(sc2.Name); } } }
//Result: //sc1 Instance //sc1 Instance
以上代码可以简化为以下形式
using System; namespace CA_StaticConstructor { class StaticClass { public static StaticClass Instance { get; set; } public string Name { get; set; } static StaticClass() { Instance = new StaticClass(); } } class Program { static void Main(string[] args) { StaticClass sc1 = StaticClass.Instance; sc1.Name = "sc1 Instance"; Console.WriteLine(sc1.Name); StaticClass sc2 = StaticClass.Instance; //Without set Name property to Instance Console.WriteLine(sc2.Name); } } } //Result: //sc1 Instance //sc1 Instance
注意上文中static StaticClass() 部分的代码,在传统的singleton中总是需要判断如第一段代码的构造,但是由于静态构造器在第一次调用的时候将会invoke,因此在后续的调用中将会保证实例的存在,即使加了也不为过,可以避免如下形式的代码破坏:
static void Main(string[] args) { StaticClass sc1 = StaticClass.Instance; sc1.Name = "sc1 Instance"; Console.WriteLine(sc1.Name); StaticClass.Instance = null; StaticClass sc2 = StaticClass.Instance; //Without set Name property to Instance Console.WriteLine(sc2.Name); }
当然按照常规我们最好不要也不应该有set方法,这样我们就可以保证我们的Instance始终是第一次调用的实例了……
using System; namespace CA_StaticConstructor { class StaticClass { private static readonly StaticClass instance; public static StaticClass Instance { get { return instance; } } public string Name { get; set; } static StaticClass() { instance = new StaticClass(); } } class Program { static void Main(string[] args) { StaticClass sc1 = StaticClass.Instance; sc1.Name = "sc1 Instance"; Console.WriteLine(sc1.Name); //StaticClass.Instance = null; StaticClass sc2 = StaticClass.Instance; //Without set Name property to Instance Console.WriteLine(sc2.Name); } } } //Result: //sc1 Instance //sc1 Instance
posted on 2007-12-10 03:10 volnet(可以叫我大V) 阅读(587) 评论(1) 编辑 收藏 举报