zoukankan      html  css  js  c++  java
  • 一个泛型的问题。

    前段时间我还在纳闷,在上上篇设计模式的单例模式中,我只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 }
  • 相关阅读:
    JAVA 主函数(主方法)
    JAVA 什么时候使用静态
    JAVA 静态成员 static
    JAVA 构造方法之间的调用
    JAVA 构造代码块
    JAVA 构造方法
    JAVA 方法重载
    JAVA 理解封装的概念,private私有的,public公有的
    JAVA this关键字
    JAVA toString方法
  • 原文地址:https://www.cnblogs.com/07lyt/p/3996506.html
Copyright © 2011-2022 走看看