public class ComType
{
    private string _name;
    
    public string Name
    {
        get{return _name;}
        set{_name=value;}
    }
}public class ComSet
{   public List<ComType> GetTypeList()
   {
      ComType thisComType=new ComType();                       //写法1
      List<ComType> list=new List<ComType>;
       .....
      foreach(DataRow theRow in DataSet.Tables["CommodityType"].Rows)
      {
          //ComType thisComType=new ComType()                 //写法2
          thisComType.Name=theRow["ComType"].ToString();
          list.Add(thisComType);
      }
      return list;
    }
}
请问下,写法1和写法2有什么区别??   能否具体描述下....  谢谢!

解决方案 »

  1.   

    1是创建一个新的对象。
    2只是更新了thisComType的Name属性为ComType列的内容
      

  2.   


     public List<ComType> GetTypeList()
      {
      ComType thisComType=new ComType(); //写法1   //实例化类ComType 得到对象thisComType
      List<ComType> list=new List<ComType>;
      .....
      foreach(DataRow theRow in DataSet.Tables["CommodityType"].Rows)
      {
      //ComType thisComType=new ComType() //写法2  //重新实例化一新对象 
      thisComType.Name=theRow["ComType"].ToString();  //更新对象thisComType的属性
      list.Add(thisComType);
      }
      return list;
      }
      

  3.   

    创建一个对象和创建Table.Rows.Count个对象
    实现的效果应该是一样的
      

  4.   

    完全不一样的意义
    写法1, 应该会产生异常吧(如果没有异常,则产生N个元素, 但这个N个元素,都指向同一个对象)
    写法2, 产生N个元素的List,每个元素指向不同的对象