C#初始化列表属性 [英] C# initialize list property

查看:222
本文介绍了C#初始化列表属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Am having below classes...how do i initialise with some values
My question is, how do i initialise above RootObject with some values in Main For example

    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

推荐答案

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

The default value for any reference type is null. So I assume you're getting a NullReferenceException when you try to add values. You can initialize your list property to an empty list in the object's constructor:

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

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

现在,RootObject的任何实例在默认情况下都将具有有效的(空)列表,允许您添加到其中:

Now any instance of RootObject will have a valid (empty) list by default, allowing you to add to it:

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

这篇关于C#初始化列表属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆