[英]The name “Monsters” doesnt exist in the current context
我對編程很陌生,遇到了一個小問題,很抱歉,如果它是一個非常簡單的解決方案,但我沒有得到它,那么我正在為實踐編寫一個非常簡單的爐石傳說版本。 我創建了一種方法,將所有5張紙牌都生成一個數組,並且嘗試使用該數組來制作一個將用作玩家套牌的列表。 但是,在我試圖在Monsters數組中進行的for循環中說,它在當前上下文中不存在?
//Generates monsters and magic cards
public static MonsterCard[] GenerateCards()
{
MonsterCard[] Monsters = new MonsterCard[5];
Monsters[0].Name = "Lizard King";
Monsters[0].Attack = 4;
Monsters[0].Health = 3;
Monsters[1].Name = "Piggy";
Monsters[1].Attack = 2;
Monsters[1].Health = 1;
Monsters[2].Name = "Great Drake";
Monsters[2].Attack = 7;
Monsters[2].Health = 5;
Monsters[3].Name = "Bear";
Monsters[3].Attack = 5;
Monsters[3].Health = 3;
Monsters[4].Name = "Lion";
Monsters[4].Attack = 6;
Monsters[4].Health = 4;
return Monsters;
}
主要():
int main(){
int number;
GenerateCards();
Random rnd = new Random();
//Player 1 deck
for (int i = 0; i < 10; i++)
{
number = rnd.Next(0, 4);
Player1.Deck[i] = Monsters[number]; //<-- this Monsters is where the problem comes
}
}
GenerateCard
返回Monsters
,但是您永遠不會在main()
本地捕獲它們。
Monster
是GenerateCards()
本地對象,並在函數完成執行后立即死亡。
int main(){
// ..
MonsterCard[] Monsters = GenerateCards();
// ..
}
上面的代碼可以解決該問題,因為您從GenerateCards()
return Monsters
,而其中包含您要在main()
內部尋找的值。
您必須將您的monsters
屬性移到全局環境中。
那是因為它在另一個方法的范圍內 ,所以它是一個局部變量,只能從此方法訪問(並且僅存在於此方法中)。
一個例子:
void m1 ()
{
int a;
//a exists
{
int b;
//a and b exist
}
//only a exists
}
//nothing exists
void m2 ()
{
//still nothing exists
int c;
//Only c exists
}
變量僅存在於其范圍內 。 這意味着,如果在方法外部定義變量,則所有方法都存在該變量:
int a;
void m1 ()
{
//a exists
}
void m2 ()
{
//a still exists
}
要了解有關此內容的更多信息,請通讀this 。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.