集合类操作:未将对象引用设置到对象的实例(二)

2015-01-27 09:57:20 · 作者: · 浏览: 21
w Test(); for (int i = 0; i < 10; i++) { TestChild tsc = new TestChild(); tsc.TestChildsCount = "10"; tsc.TestChildsId = Guid.NewGuid().ToString(); tsc.TestChildsName = "name"; ts.TestChilds.Add(tsc); } int ss = ts.TestChilds.Count; } } }


小注:这个错误在操作集合类Collection、List时,均会出现,原因是:Test类的属性没有实例化,在添加数据之前给它实例化一下,具体代码如下:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace TestSet
{
    public class Test
    {
        public Test()
        {
            //
        }
        private List
  
    _TestChilds;
        /// 
    /// 子类 /// 
        public List
   
     TestChilds { //以下代码为修正代码 get { if (_TestChilds == null) { _TestChilds = new List
    
     (); } return _TestChilds; } set { _TestChilds = value; } } } }