前段时间我还在纳闷,在上上篇设计模式的单例模式中,我只New过一次对象。但是查看我分明得到了2个或多个不同的对象。今天做个试验。代码如下
通过实验发现,对象确实是new了两次,initial确实是进入了两次,对于不同泛型对象,是要重新开辟内存的。
下面的文章做个资料保存。
http://www.cnblogs.com/DebugLZQ/archive/2012/09/03/2669383.html
http://msdn.microsoft.com/en-US/library/f4a6ta2h(v=vs.80).aspx
1usingSystem;2usingSystem.Collections.Generic;3usingSystem.Linq;4usingSystem.Text;56namespaceConsoleapplication107{8classPRogram9{10staticvoidMain(string[] args)11{12generictest<custom1>.List.Add(newcustom1("custom1(1)"));13generictest<custom1>.List.Add(newcustom1("custom1(2)"));14generictest<custom2>.List.Add(newcustom2("custom2(1)"));15generictest<custom2>.List.Add(newcustom2("custom2(2)"));16Console.ReadKey();17}18}19classgenerictest<T>20{21privategenerictest()22{ }23staticprivateList<T> list=null;24staticpublicList<T>List25{26set27{2829list =value;30}31get32{33if(list ==null)34{35initial();36}37returnlist;38}39}4041privatestaticvoidinitial()42{43list =newList<T>();44}45}46classcustom147{48publicstringstr;49publiccustom1(stringstr)50{51this.str=str;52}53}54classcustom255{56publicstringstr;57publiccustom2(stringstr)58{59this.str=str;60}6162}63}