提问人:exaudio 提问时间:1/25/2017 更新时间:1/25/2017 访问量:26
给定一个对象的属性是对象数组,如何在 C# 中设置该属性的特定实例?[复制]
Given an object with a property that is an array of objects, how does one set a specific instance of said property in C#? [duplicate]
问:
我有两个对象:“Table”和“Record”。“Table”具有属性“Items”,该属性是“Record[]”类型的数组。
如何设置“Table”的特定实例的“Items”属性(例如,table.Items[0]) 添加到“Record”的特定实例(例如,first_record)?
我尝试按如下方式对其进行编码,但我的代码导致“NullReferenceException 未处理”错误。
Record first_record = new Record();
first_record.Field1 = "r1f1";
first_record.Field2 = "r1f2";
first_record.Field3 = "r1f3";
Record second_record = new Record();
second_record.Field1 = "r2f1";
second_record.Field2 = "r2f2";
second_record.Field3 = "r2f3";
Table table = new Table();
table.Items[0] = first_record;
table.Items[1] = second_record;
谢谢
答:
0赞
exaudio
1/25/2017
#1
Stackoverflow 提出了一个类似的问题,为我提供了答案。我无法初始化数组。这是我错过的那一行:
table.Items = new Record[2];
将该行插入到我原始问题的代码中会导致以下内容:
Record first_record = new Record();
first_record.Field1 = "r1f1";
first_record.Field2 = "r1f2";
first_record.Field3 = "r1f3";
Record second_record = new Record();
second_record.Field1 = "r2f1";
second_record.Field2 = "r2f2";
second_record.Field3 = "r2f3";
Table table = new Table();
table.Items = new Record[2];
table.Items[0] = first_record;
table.Items[1] = second_record;
这成功了。谢谢 Stackoverflow!
评论
Table
Record