raa*_*esh -4 c# properties list
我有以下类...我如何初始化一些值
我的问题是,我如何在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
Run Code Online (Sandbox Code Playgroud)
Dav*_*vid 10
任何引用类型的默认值为null.因此,我假设您在NullReferenceException尝试添加值时获得了一个.您可以将list属性初始化为对象构造函数中的空列表:
public class RootObject
{
public List<Inchistory> inchistory { get; set; }
public RootObject()
{
inchistory = new List<Inchistory>();
}
}
Run Code Online (Sandbox Code Playgroud)
现在任何实例RootObject都默认有一个有效(空)列表,允许你添加它:
Rootobject robj = new Rootobject();
robj.inchistor.Add(someInstanceOfInchistory);
Run Code Online (Sandbox Code Playgroud)