C#嵌套对象属性

时间:2015-08-03 01:13:29

标签: c# object properties nested

您好我在C#中使用返回对象的嵌套属性进行一些测试,但是我得到了一个对象引用异常。

我希望能够在嵌套的属性中访问数组,但在当前上下文中,我可以看到我没有在属性中实例化任何新对象。

这是基本问题出现的地方......我在哪里宣布一个新的'对象实例在这一切的中间?我甚至需要在“foo”中声明和新的对象引用。班级或者' bar'类?

namespace CustomProperties_TEST
{
    class Program
    {
        public foo[] Blatherskite { get; set; }

        static void Main(string[] args)
        {
            Program myProgram = new Program();

            myProgram.Blatherskite[0].CustomProperty1[0].CustomProperty2 = 999999999;
            myProgram.Blatherskite[1].CustomProperty1[0].CustomProperty2 = 999999999;

            foreach (var item in myProgram.Blatherskite)
            {
                Console.WriteLine(item.CustomProperty1[0].CustomProperty2);
            }
        }
    }

    class foo
    {
        private bar[] customevariable1;

        public bar[] CustomProperty1
        {
            get { return customevariable1; }
            set { customevariable1 = value; }
        }
    }

    class bar
    {
        private int customintvariable2;

        public int CustomProperty2
        {
            get { return customintvariable2; }
            set { customintvariable2 = value; }
        }
    }
}

1 个答案:

答案 0 :(得分:1)

您可能希望执行以下操作,因为默认情况下数组已初始化为null

static void Main(string[] args)
{
    Program myProgram = new Program();

    // This is your missing initialization
    myProgram.Blatherskite = new foo[2] {
          new foo{CustomProperty1 = new bar[2]{new bar{CustomProperty2 = 1},new bar{CustomProperty2 = 2}}}
        , new foo{CustomProperty1 = new bar[2]{new bar{CustomProperty2 = 3},new bar{CustomProperty2 = 4}}}};

    myProgram.Blatherskite[0].CustomProperty1[0].CustomProperty2 = 999999999;
    myProgram.Blatherskite[1].CustomProperty1[0].CustomProperty2 = 999999999;

    foreach (var item in myProgram.Blatherskite)
    {
        Console.WriteLine(item.CustomProperty1[0].CustomProperty2);
    }
}

使用数组意味着您必须设置它们的大小。如果您想要更灵活,请使用List,然后您只需向其中添加项目即可。