1 回答

TA貢獻2037條經驗 獲得超6個贊
在下面的示例中,我在 MainGame 類本身中創建并存儲了一個 MainGame 實例。因為這是從靜態 Main() 完成的,所以聲明也必須是靜態的。請注意,如果進行了此聲明public,則可以使用語法從任何地方訪問它MainGame.mg(但是,這不是推薦的方法)。
接下來,我們通過該行中的 Constructor 將該 MainGame 實例傳遞給MainConsole表單Application.Run()。請注意下面發布的 MainConsole 中的附加構造函數。返回類型中的“ref”checkCommands()已被刪除,因為可以在 MainConsole 本身中使用傳遞和存儲的對 MainGame 的引用更改該值。
主游戲類:
public class MainGame
{
public string Connected_IP = " ";
public short Is_Connected = 0;
static MainGame mg = null; // instantiated in Main()
static void Main()
{
mg = new MainGame(); // this instance will be worked with throughout the program
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new MainConsole(mg)); // pass our reference of MainGame to MainConsole
}
public string checkCommands(string command) // no "ref" on the return type
{
IP_DataBase ips = new IP_DataBase();
/*checking for ips in the list*/
string[] dump;
if (command.Contains("connect"))
{
dump = command.Split(' ');
for (int i = 0; i < ips.IPS.Length; i++)
{
if (dump[1] == ips.IPS[i])
{
Connected_IP = dump[1];
Is_Connected = 1;
break;
}
else
{
Connected_IP = "Invalid IP";
Is_Connected = 0;
}
}
}
else if (command.Contains("quit")) /*disconnect command*/
{
Connected_IP = "Not Connected";
Is_Connected = 0;
}
return Connected_IP;
}
}
在這里,在 MainConsole 表單中,我們添加了一個額外的構造函數來接收 MainGame 的實例。有一個名為mMainGame 類型的字段,但請注意,在這種形式中,我們實際上沒有使用“new”創建 MainGame 的實例;我們只使用傳入的實例。對 MainGame 的引用存儲在m構造函數中,以便它可以在代碼的其他點使用:
public partial class MainConsole : Form
{
// Note that we are NOT creating an instance of MainGame anywhere in this Form!
private MainGame m = null; // initially null; will be set in Constructor
public MainConsole()
{
InitializeComponent();
}
public MainConsole(MainGame main)
{
InitializeComponent();
this.m = main; // store the reference passed in for later use
}
private void ConsoleInput2_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Return && ConsoleInput2.Text.Trim().Length > 0)
{
// Use the instance of MainGame, "m", that was passed in:
Text_IP_Connected.Text = m.checkCommands(ConsoleInput2.Text);
vic_sft.Enabled = (m.Is_Connected == 1);
}
}
}
- 1 回答
- 0 關注
- 89 瀏覽
添加回答
舉報