C#初始化列表属性

时间:2014-09-18 18:26:32

标签: c# list properties

我有以下课程...如何初始化一些值
        我的问题是,如何使用Main中的一些值初始化RootObject之上         例如

    Rootobject robj = new Rootobject();
    robj.inchistor.Add()     



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

    namespace JsonSample3
    {

        public class Customerinfo
        {
            public string customername { get; set; }
            public string address { get; set; }
            public string postcode { get; set; }
        }

        public class Inchistory
        {

            public Customerinfo customerinfo { get; set; }
            public string r { get; set; }
            public string reference { get; set; }
            public string region { get; set; }

        }

        public class RootObject
        {
            public List<Inchistory> inchistory { get; set; }
        }


    }

    class Program
    {
            static void Main(string[] args)
            {
               RootObject robj = new RootObject{ r = "", }

            }
    }



   Am having above classes namely CustomerInfo, Inchistory and Rootobject

2 个答案:

答案 0 :(得分:9)

任何引用类型的默认值为null。所以我假设你在尝试添加值时得到NullReferenceException。您可以将list属性初始化为对象构造函数中的空列表:

public class RootObject
{
    public List<Inchistory> inchistory { get; set; }

    public RootObject()
    {
        inchistory = new List<Inchistory>();
    }
}

现在RootObject的任何实例默认都有一个有效(空)列表,允许你添加它:

Rootobject robj = new Rootobject();
robj.inchistor.Add(someInstanceOfInchistory);

答案 1 :(得分:0)

不确定你在问什么。您在寻找对象和集合初始化的组合吗?

RootObject robj = new RootObject() 
{
    inchistory = new List<Inchistory>() 
    {
       new Inchistory() 
       {
           r = "foo",
           reference = "bar",
           customerinfo = new CustomerInfo()
           {
                customername = "joe blogs",
                address = "somewhere",
                postcode = "xxx xxxx"
           },
           region = "somewhere"
       },
       new Inchistory()
       {
           // etc
       }
    }
};

或者,如果您现在没有要添加的内容,您可以这样做:

RootObject robj = new RootObject() 
{
    inchistory = new List<Inchistory>() 
};

或者你可以像David建议的那样在类构造函数中初始化列表。