2017-04-20 56 views
0

我在Visual Studio中創建了一個Pokemon類型的遊戲。我正在處理庫存表單。使用公共整數變量作爲計數器C#

我的問題是我可以使用公共計數變量作爲跟蹤庫存的方法嗎?

設置它:

public int healthPotionCount = 0; 

然後,如果玩家遇到healthPotion增加它的最後使用同一公共變量來確定是否要顯示它的庫存價值

if(picPlayer.Bounds.IntersectsWith(hPotion.Bounds) 
     { 
      healthPotionCount++; 
     } 

if(healthPotionCount > 0) 
    { 
     picBox.BackgroundImage = (the health potion image); 
     lblQuantity.Text = ""+healthPotionCount; 
    } 

有了這個,我的問題是我的解決方案中有很多表單和我希望這個變量可以被任何形式訪問。這種邏輯難以奏效嗎?

回答

0

有了這個,我的問題是,我有我的解決方案 許多表格,我希望這個變量可以通過任何形式訪問。

你可以使它成爲static這意味着它屬於類而不是特定的表單對象,因此你可以在多個表單中訪問它。

public static int healthPotionCount { get; set;} 
+0

嗨,所以在我的全局變量類記載: 類healthPotion { 公共靜態INT healthPotionCount = 0; } 但我仍然無法稱之爲另一種形式使用 MessageBox.Show(「」+ healthPotionCount); – Tarheel81

+0

@ Tarheel81爲了以另一種形式訪問它,你需要指定表單的名稱,然後是變量,即如果你想從form2訪問它,你可以執行'Form1.healthPotionCount'。 –

+0

@ Tarheel81hi,iam new但我想我是爲什麼不在全局變量類中使用'get''set'。 http://stackoverflow.com/questions/5096926/what-is-the-get-set-syntax-in-c – chopperfield