2010-12-05 103 views
2

對不起菜鳥問題,因爲我剛剛開始使用C#。C#,對象問題

我有一個類

namespace WindowsFormsApplication1 
{ 
    class people 
    { 
     public int Cash; 
     public string LastName; 
     public void GiveCash(int amount) { this.Cash = this.Cash - amount; } 
     public void ReceiveCash(int amount) { this.Cash = this.Cash + amount; } 

    } 
} 

我初始化兩個Object它。

public partial class Form1 : Form 
{ 
    public Form1() 
    { 
     InitializeComponent(); 
     people viktor = new people() { Cash = 1000, LastName = "Jushenko" }; 
     people julia = new people() { Cash = 500, LastName = "Timoshenko" }; 
    } 

但後來在代碼中,我無法訪問任何這些對象。 比如我,我使用

private void button1_Click(object sender, EventArgs e) 
    { viktor.cash = 200; } 

它類似於「名稱‘勝利者’並不在這方面存在的......」我到底做錯了什麼?

謝謝!

+0

一個次要的事情,在C#中的名稱類的首字母大寫`人` – 2010-12-05 19:39:30

回答

3

您在Form1構造函數聲明局部變量。超出範圍後您無法訪問它們。您應聲明它們在類領域的,就像這樣:

public partial class Form1 : Form 
{ 
    private people viktor; 
    private people julia; 
    public Form1() 
    { 
     InitializeComponent(); 
     viktor = new people() { Cash = 1000, LastName = "Jushenko" }; 
     julia = new people() { Cash = 500, LastName = "Timoshenko" }; 
    } 

字段viktorjulia現在是你的類的一部分,並可以從類中的方法來訪問它們。

+0

感謝,它工作! :) – Rob 2010-12-05 19:41:08

1

您的victor變量的範圍局部於Form1構造函數,不能在其外部訪問。

您需要將它提升一個領域,如果你想訪問它在事件處理程序:

private people viktor; 

public Form1() 
{ 
    InitializeComponent(); 
    viktor = new people() { Cash = 1000, LastName = "Jushenko" }; 
    people julia = new people() { Cash = 500, LastName = "Timoshenko" }; 
} 

private void button1_Click(object sender, EventArgs e) 
{ 
    viktor.cash = 200; 
    // Note: the "julia" variable is not in scope here. 
} 
+0

感謝,它工作! :) – Rob 2010-12-05 19:50:13

1

有不同的範圍,你需要注意。你無法訪問你的變量的原因是因爲它們在你無法訪問的範圍內。

一個解決方案是移動的變量,他們的電流範圍:它的標準例如

public partial class Form1 : Form 
{ 
    private people victor = null; 
    private people julia = null; 
    public Form1() 
    { 
     InitializeComponent(); 
     this.viktor = new people() { Cash = 1000, LastName = "Jushenko" }; 
     this.julia = new people() { Cash = 500, LastName = "Timoshenko" }; 
    } 
.... 
+0

感謝,它工作! :) – Rob 2010-12-05 19:49:52