你好,我正在用C#做一些带有返回对象的嵌套属性的测试,但是我得到了一个对象引用异常。
我希望能够访问嵌套属性中的数组,但在当前上下文中,我可以看到我没有在属性中实例化任何新对象。
这就是基本问题出现的地方……我该在哪里声明一个'new‘对象实例呢?我甚至需要在'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; }
}
}
}发布于 2015-08-03 09:29:46
您可能希望执行类似以下的操作,因为默认情况下数组初始化为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,然后您可以简单地向其中添加项。
https://stackoverflow.com/questions/31778180
复制相似问题