【发布时间】:2016-07-20 16:58:32
【问题描述】:
我的 C# 程序需要接收 xml 数据并将其存储在 sql 数据库中。我有很多说明的批次。我因此实现了这些类:
class Batch
{
public string batchUID { get; set; }
public Instruction[] instructionArray { get; set; }
}
class Instruction
{
public string instructionUID { get; set; }
}
我的程序是这样运行的
Batch myBatch = new Batch();
myBatch.instructionArray = new Instruction[3];
myBatch.instructionArray[0] = new Instruction();
SomeFunc(myBatch.instructionArray[0]);
public void SomeFunc(Instruction instruction)
{
// How do I do the following?
console.write( instruction.OWNER.batchUID )
}
我尝试过广泛搜索,但每个结果都与继承、内部/外部类等有关。如果可能,我想避免在类指令中创建 batchUID 方法。
【问题讨论】:
-
new Instruction[3]只是调整数组大小,所有值都是null,其中没有Instruction实例。您必须创建它们,而最好的时机是将父级作为参数传递给Instruction的构造函数。 -
你必须以某种方式设置你的指令。
myBatch.instructionArray[2] = new Instruction { instructionUid = "foo" }; -
我是否实例化 myBatch.instructionArray[n] 对我的问题没有影响...
-
@p4ndepravity 但是您提供的代码示例有一个严重的错误,只会导致
NullReferenceException。所以我必须在你遇到麻烦之前指出这一点。
标签: c# .net class parent-child has-many