【问题标题】:Must be used before declaration必须在申报前使用
【发布时间】:2021-07-15 13:58:29
【问题描述】:

我正在尝试制作主机游戏,但我对以下代码(以及未来代码)有疑问

Node n1 = new Node("You Are in a Snowy biome, you notice your Crashed Vehicle behind you.", map1, n9, n2, null, n3, null, null, "You Notice Your Crashed Vehicle, it is Beyond use now.", null);

Node n2 = new Node("You Notice a Metal Lamp Post Standing Tall, the Light is on.", map2, n8, n4, null, n1, "You Move Past the Lamp Post.", null, "You see Part of your Crashed Vehicle, it was Pretty Long.", "This was where you Crashed.");

Node n3 = new Node("You Notice a Box with a Red Plus Sign on it.", map3, n10, n1, null, null, "You Walk Towards the box and open the Lid...", ItemN3.GetItem());

Node n4 = new Node(null, map4, n7, n5, null, n2, null, null, "A huge Wall of Fire Blocks the whole of the South.", "You Move back To the Lamp Post.");

Node n5 = new Node("You See A massive hole to the East.", map5, n6, null, null, n4, "You See the hole, Around 54ft Deep.", null, "The Wall of Fire Continues.", null);

节点采用这些参数:

但是我有错误告诉我在声明之前我不能使用Node,但是当我将它移到错误上方时,我在更下方的其他节点之一上得到相同的错误。所以它只是一个无限循环的错误。 我不知道如何解决这个问题。如果可能,请有人帮忙吗?

【问题讨论】:

  • 我的建议:停止在构造函数中做所有事情。构造后分配属性,或引入接受邻居的方法。
  • @Llama 所以你想让我做一个单独的方法来创建节点?
  • @Isparia OP 在 n1 的构造函数中引用了 n9、n2 和 n3。在 n2 中,他们引用了 n1。
  • @Llama 你是对的,如果我将对象构造为空然后我运行一个采用所有参数的方法,它将起作用。谢谢你:))

标签: c# oop console


【解决方案1】:

你的问题是你的情况是先有鸡还是先有蛋。我会用这个类简化你的例子:

public class Node
{
    public Node(Node neighbour)
    {
    }
}

那么你实际上是在这样做:

Node n1 = new Node(n2);
Node n2 = new Node(n1);

显然这是行不通的,因为在使用对象之前需要对其进行初始化。您可以创建节点,然后分配属性:

public class Node
{
    public Node Neighbour {get;set;}
}

然后像这样初始化它们:

Node n1 = new Node();
Node n2 = new Node();
n1.Neighbour = n2;
n2.Neighbour = n1;

如果您的方向始终是基数,您可能会创建一个二维数组 (Node[,]),然后在初始化所有节点后自动循环分配邻居。

【讨论】:

  • 这正是我现在所做的。非常感谢,这让我花了很长时间才弄清楚。 :)))
【解决方案2】:

简化你的代码,问题来了:

Node n1 = new Node(n2);

Node n2 = new Node(n8);

您在声明或初始化 n2 之前尝试使用它。

相反,有一个方法或属性来完成赋值,例如

public class Node
{
    public void Next(Node n) ...
}

Node n1 = new Node();    
Node n2 = new Node();
n1.Next(n2);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-03-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-11-20
    • 1970-01-01
    相关资源
    最近更新 更多