2017-05-23 131 views
-6

所以,我得到這個作爲一個錯誤存在:變量不會在目前情況下

The name p1 does not exist in the current context.

它指的是代碼行中Attack()Player類。

namespace GameOne 
{ 
    public class Program 
    { 
     public static void Main() 
     { 
      Ai [] badguys = new Ai [5]; 
      Player p1 = new Player(); 
     } 
    } 

    public class Ai 
    { 
     public Ai() 
     { 
      int Health = 10; 
      int Damage = 1; 
     } 

     public static int Attack() 
     { 
      p1.Health--; 
      return p1.Health; 
     } 
    } 

    public class Player 
    { 
     public Player() 
     { 
      int Health = 50; 
     } 
    } 
} 
+0

'p1'是'Main()'中的局部變量。 'Attack()'沒有定義一個名爲'p1'的符號。 – xxbbcc

+1

當您發佈代碼時,請仔細檢查並確保所有代碼格式正確,縮進一致,並刪除多餘的空行以提高可讀性。 – crashmstr

+0

總是嘗試在詢問之前在線搜索錯誤,以下文章可能會有幫助: https://stackoverflow.com/questions/41974155/the-name-does-not-exist-in-the-current-context –

回答

0

p1超出了攻擊方法的範圍。您在main中聲明它(作爲隱式私有)對象,所以它對Attack方法不可見。攻擊()只是根本不知道p1是什麼。

1

由於@xxbbcc聲明p1是Main()中的局部變量,所以Attack對p1一無所知。

爲了使你的代碼的工作,你可以進入到p1.Health攻擊:

public static int Attack(int health) 
{ 
    health--; 
    return health; 
} 

此外:

int Health = 10; 
    int Damage = 1; 

是本地的AI,所以如果你打算使用它們AI之外,那麼你會遇到同樣的問題。

相關問題