如何引用尚未实例化的对象

时间:2014-04-28 23:23:00

标签: c# instantiation

我试图用C#建模流程图。我会稍微简化一下类,但基本的想法是给定的Step指向另一个Step。我想要做的是在代码中的一个地方建立连接。例如,我希望step1指向step2,指向step3

class Step
{
   Step nextStep;

   // Constructor
   public Step(Step nextStep) { this.nextStep = nextStep; }
}

class Chart
{
    private readonly Step step1;
    private readonly Step step2;
    private readonly Step step3;

    public Chart()
    {
        step1 = new Step(step2);
        step2 = new Step(step3);
        step3 = new Step(null);
    }
}

static void main()
{
   Chart myChart = new Chart();
}

这编译很好,但如果nextStep对象尚未实例化,则实例化时引用将丢失。

在此示例中,step1的构造函数已传递step2,此时为null。我希望在实例化step2时,step1中的引用会正确指向新创建的step2,但它不会。

看起来我需要首先实例化所有对象,然后返回并通过setter或其他类似设置链接。这是正确的方法吗?或者可以在我尝试的时候在构造函数中完成它?

3 个答案:

答案 0 :(得分:4)

您需要创建一个不指向任何其他内容的实际对象。

step3 = new Step(null);

从那里开始,按相反的顺序设置步骤,直到达到第一步。

step2 = new Step(step3);
step1 = new Step(step2);

答案 1 :(得分:4)

您可能需要向后工作:step3首先,然后step2在其构造函数中解决step3等。

答案 2 :(得分:2)

如果要在构造函数中执行此操作,则必须首先创建对象。使用依赖注入的一种方法是传入父级并将新步骤指定为父级的下一步。

示例:

class Step
{
    private Step nextStep;

    public Step() {}

    public Step(Step parent)
    {
        parent.nextStep = this;
    }
}

static void main()
{
    Step step1, step2, step3;

    step1 = new Step();
    step2 = new Step(step1);
    step3 = new Step(step2);
}
相关问题