簡體   English   中英

必須在聲明前使用

[英]Must be used before declaration

我正在嘗試制作一個控制台游戲,但我對以下代碼(以及未來的代碼)有疑問

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 ,但是當我將它移到錯誤上方時,我在其他節點之一上得到相同的錯誤。 所以它只是一個無限循環的錯誤。 我不知道如何解決這個問題。 如果可能,請有人幫忙嗎?

簡化您的代碼,這是問題所在:

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);

你的問題是你有雞和蛋的情況。 我將用這個類簡化你的例子:

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[,] ),然后在初始化所有節點后自動循環分配鄰居。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM