[英]C# nested object properties
Hello I am doing some tests in C# with nesting properties which return objects, but I am getting an object reference exception. 您好,我正在C#中使用返回对象的嵌套属性进行一些测试,但是我遇到了对象引用异常。
I want to be able to access the arrays in nested Properties, but in the current context I can see that I'm not instancing any new objects inside the properties. 我希望能够访问嵌套属性中的数组,但是在当前上下文中,我可以看到我没有实例化属性内的任何新对象。
This is where the basic question comes up... Where do I declare a 'new' object instance in the middle of all this? 这是基本问题出现的地方...在所有这些中间,我应该在哪里声明“新”对象实例? Do I even need to declare and new object reference inside the 'foo' class or 'bar' class? 我什至需要在'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; }
}
}
}
You would want to do something like the following, since arrays are initialized to null
by default. 您将要执行以下操作,因为默认情况下数组会初始化为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);
}
}
Using arrays means you'll have to set their size. 使用数组意味着您必须设置它们的大小。 If you would want more flexibility, use a List
, and then you can simply add items to it. 如果您想要更大的灵活性,请使用List
,然后可以简单地向其中添加项目。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.