我有两个对象:'表'和'记录'。 'Table'有一个属性'Items',它是一个'Record []'类型的数组。
如何将“Table”的特定实例(例如table.Items [0])的“Items”属性设置为“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 :(得分:0)
Stackoverflow建议similar question提供了我的答案。我没能初始化数组。这是我失踪的那条线:
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!