·您现在的位置: 云翼网络 >> 文章中心 >> 网站建设 >> 网站建设开发 >> ASP.NET网站开发 >> 一个泛型的问题。

一个泛型的问题。

作者:佚名      ASP.NET网站开发编辑:admin      更新时间:2022-07-23

前段时间我还在纳闷,在上上篇设计模式的单例模式中,我只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

 1 using System;
 2 using System.Collections.Generic;
 3 using System.Linq;
 4 using System.Text;
 5 
 6 namespace Consoleapplication10
 7 {
 8     class PRogram
 9     {
10         static void Main(string[] args)
11         {
12             generictest<custom1>.List.Add(new custom1("custom1(1)"));
13             generictest<custom1>.List.Add(new custom1("custom1(2)"));
14             generictest<custom2>.List.Add(new custom2("custom2(1)"));
15             generictest<custom2>.List.Add(new custom2("custom2(2)"));
16             Console.ReadKey();
17         }
18     }
19     class generictest<T>
20     {
21         private generictest()
22         { }
23         static private List<T> list=null;
24          static public List<T> List
25          {
26              set
27              {
28 
29                  list = value;
30              }
31              get
32              {
33                  if (list == null)
34                  {
35                      initial();
36                  }
37                  return list;
38              }
39          }
40 
41          private static void initial()
42          {
43              list = new List<T>();
44          }
45     }
46     class custom1
47     {
48         public  string str;
49         public custom1(string str)
50         { 
51         this.str=str;
52         }
53     }
54     class custom2
55     {
56      public  string str;
57         public custom2(string str)
58         { 
59         this.str=str;
60         }
61     
62     }
63 }