首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >C#嵌套对象属性

C#嵌套对象属性
EN

Stack Overflow用户
提问于 2015-08-03 09:13:29
回答 1查看 1.3K关注 0票数 0

你好,我正在用C#做一些带有返回对象的嵌套属性的测试,但是我得到了一个对象引用异常。

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

这就是基本问题出现的地方……我该在哪里声明一个'new‘对象实例呢?我甚至需要在'foo‘类或'bar’类中声明和新的对象引用吗?

代码语言:javascript
复制
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; }
        }
    }
}
EN

回答 1

Stack Overflow用户

发布于 2015-08-03 09:29:46

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

代码语言:javascript
复制
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,然后您可以简单地向其中添加项。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/31778180

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档