2013-10-07 215 views
0

我遇到了使用在「Form1_Load」中聲明的數組的問題。我的目標是能夠將值分配給數組,然後從數組中減去某些值。這個數組是一個結構數組。我想我必須在其他地方公開聲明數組。現在我想嘗試在「Form1_load」中完成大部分操作。將類分配給結構數組c#

我想要實現的是如果用戶點擊一張圖片,它應該更新剩下多少項目(從20開始)並將總數添加到標籤。有5個不同的圖片,他們可以點擊這樣做,這是陣列需要的地方。

結構:

 struct Drink 
    { 
     public string name; 
     public int cost; 
     public int numberOfDrinks = 20; 
    } 
  • 結構是命名空間內,部分類的上方。 *

加載事件:

 private void Form1_Load(object sender, EventArgs e) 
    { 
     const int SIZE = 5; 
     Drink[] drink = new Drink[SIZE]; 


    } 
  • 這就是我想要的數組*

這裏,如果點擊畫面會發生什麼一個例子:

 private void picCola_Click(object sender, EventArgs e) 
    { 
     drink[0].cost = 1.5; 
     drink[0].name = ""; 
    } 
  • 但是,在當前上下文中不存在消息「The name'drink'」。數組是否需要公開?
+4

可變的結構是邪惡的。這應該幾乎可以肯定是一個類,而不是一個結構,因爲你正在使用它以及它是如何被使用的。 – Servy

+0

我想你應該看看[結構和類有什麼區別](http://stackoverflow.com/questions/13049/whats-the-difference-between-struct-and-class-in-net) –

回答

6

當您在函數Form1_Load中聲明數組飲料時,它僅在該函數中成爲本地函數。沒有人能看到它。您需要更改變量的範圍以成爲全局變量(不需要公開)。

private Drink[] drink; 
private void Form1_Load(object sender, EventArgs e) 
    { 
     const int SIZE = 5; 
     drink = new Drink[SIZE]; 
    } 

但是,您可以在其他地方實例化它。

5
public partial class Form1 : Form 
{ 
    public Drink[] drinks; 
    public const int SIZE = 5; 

    private void Form1_Load(object sender, EventArgs e) 
    { 
     drinks = new Drink[ SIZE ]; 
    } 

    private void picCola_Click(object sender, EventArgs e) 
    { 
     drinks[0].cost = 1.5; 
     drinks[0].name = ""; 
    } 
} 

您需要正確範圍你的對象!通過在Form1_Load中聲明它,當其他方法被調用時它不存在。你必須把它放在類的範圍級別(從而使其成爲字段)。以下:

{ 
    int a = 7; 
    { 
     int b = 5; 
     { 
      int c = 6; 

      a = 1; // OK: a exists at this level 
      b = 2; // OK: b exists at this level 
      c = 3; // OK: c exists at this level 
     } 

     a = 1; // OK: a exists at this level 
     b = 2; // OK: b exists at this level 
     c = 3; // WRONG: c does not exist at this level 
    } 

    a = 1; // OK: a exists at this level 
    b = 2; // WRONG: b does not exist at this level 
    c = 3; // WRONG: c does not exist at this level 
} 

a = 1; // WRONG: a does not exist at this level 
b = 2; // WRONG: b does not exist at this level 
c = 3; // WRONG: c does not exist at this level 
0

結構類型的變量或存儲位置基本上是一堆用膠帶粘在一起變量如果一個聲明struct pair{public int X,Y};然後一個指定變量聲明pair myPair;將有效地聲明瞭兩個int variables-- myPair.X。和myPair.Y - 雖然可以將它們用作pair時方便。如果聲明pair[] myArray,則該陣列的每個項目myArray[index]將保存兩個整數,即myArray[index].XmyArray[index].Y

其目的是表現爲一堆變量與膠帶粘在一起的結構應該簡單地將這些變量聲明爲公共字段(暴露字段結構是表示該行爲的最佳數據類型)。旨在用於其他目的的結構應經常遵循MS指南。我不清楚你打算如何使用你的數據類型,所以我不能說一個結構是否合適,儘管在一個struct定義中初始化numberOfDrinks將不起作用。當一個類被要求創建一個自己的實例時,Class對象實例和它們的字段纔會存在 - 這個類可以控制這個實例。相比之下,結構定義則指出結構類型的存儲位置應該被視爲一堆粘在一起的變量,但它是該存儲位置的所有者,而不是結構類型,它控制着它的結構創建。