[英]How can I create an instance of a class that I can use is more than one place in c#
所以我一直在研究一個詳細介紹大學生的課程。 我有一個按鈕,用於將詳細信息設置為類的新實例,另一個用於檢查學生是否通過我的類中的方法傳遞。 問題是我在第一個按鈕中創建了一個類的實例,以便從用戶輸入的內容中添加值,但是我不能使用第二個按鈕來訪問在第一個按鈕中創建的類的實例。
嘗試通過類似方法創建屬性
private Student student1 {get;set;}
然后,您可以使用在此屬性中設置的實例
student1 = new Student();
如果您希望能夠從此類外部訪問該屬性,則可以將其設置為公共,並且即使沒有您實際使用的類的實例,也可以在該字段可訪問時將其設置為靜態(大多數可能是一種形式)。
那么,您當然不應該在另一個按鈕中創建一個新學生。 當您將該屬性設置為新學生時,您第一次設置的舊學生將會離開。
Static或Singleton類應該解決這個問題。 http://msdn.microsoft.com/en-us/library/ff650316.aspx-Singleton實現
更簡單的方法也是類屬性。 http://msdn.microsoft.com/en-us/library/w86s7x04.aspx - 類屬性
Student student1; //**Simple Declare it here then**
private void button3_Click(object sender, EventArgs e)
{
student1 = new Student(); //**Create a new instance here**
**//BUT You need to handle the exception that can come if the user clicks //button1 before button 3** possibly like this
if(student1 == null)
return;
label1.Text = student1.text();
if (student1.hasPassed() == true)
{
passfailtextbox.Text = "Pass";
}
else
{
passfailtextbox.Text = "Fail";
}
}
private void button1_Click(object sender, EventArgs e)
{
Student student1 = new Student();
student1.FirstName = firstnamebox.Text;
student1.SecondName = secondnamebox.Text;
student1.DateofBirth = DateTime.Parse(dobtextbox.Text).Date;
student1.Course = coursetextbox.Text;
student1.MatriculationNumber = int.Parse(matriculationtextbox.Text);
student1.YearMark = double.Parse(yearmarktextbox.Text);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.