[英]C# Accessing the same instance of a child form from 2 methods in the parent form
到目前為止,我已經有了此代碼,希望能夠以子窗體形式調用相同的函數。
家長表格代碼:
FormGame frmGame; // i put this here so that in the second function it doesnt complain about frmGame not being set.
public void CreateGame(string Level) // this function is called first
{
FormGame frmGame = new FormGame(this); // i need both functions to be able to access this instance of the child form
frmGame.SetLevel(Level); // sets the text of a label in the child form
frmGame.Show();
}
public void UpdateGame(string Level) // then this function is called second
{
frmGame.SetLevel(Level); // to update the same label as set in the first method
}
這段代碼的問題是,雖然是的,但是當它坐在那里時並沒有出現任何錯誤,但是在調用第二個函數時對其進行調試時,它找不到在第一個函數中設置的FormGame實例,因此frmGame為null 。
我努力了:
您的代碼創建一個FormGame
的新實例,其范圍僅在該函數內部。 這絕不會影響您在方法外部定義的frmGame
變量。
FormGame frmGame = new FormGame(this);
為避免在調用UpdateGame
時UpdateGame
,請不要在方法內部定義新變量。
public void CreateGame(string Level)
{
frmGame = new FormGame(this); // use the class-level field
...
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.