给定一个带有 属性 的对象,它是一个对象数组,如何在 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#?
我有两个对象:'Table' 和 'Record'。 'Table' 有一个 属性 'Items',它是一个 'Record[]' 类型的数组。
如何将 'Table' 的特定实例(例如 table.Items[0])的 'Items' 属性 设置为 [=23 的特定实例=](例如,first_record)?
我尝试按如下方式编写代码,但我的代码导致 "NullReferenceException was unhandled" 错误。
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;
谢谢
Whosebug 建议 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;
成功了。谢谢 Whosebug!
我有两个对象:'Table' 和 'Record'。 'Table' 有一个 属性 'Items',它是一个 'Record[]' 类型的数组。
如何将 'Table' 的特定实例(例如 table.Items[0])的 'Items' 属性 设置为 [=23 的特定实例=](例如,first_record)?
我尝试按如下方式编写代码,但我的代码导致 "NullReferenceException was unhandled" 错误。
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;
谢谢
Whosebug 建议 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;
成功了。谢谢 Whosebug!