在另一个窗体中调用一个窗体的方法
Calling a method of a form inside another form
在我的主窗体中:
partial class Form1 : Form
我有这个方法:
public void SendLog();
另一个class里面:class Player
我有一个方法,我想从 Form1
调用 SendLog()
public void Print()
{
Form1.SendLog(); // Error: An object reference is required for the non-static field, method, or property 'Form1.SendLog(string)'
}
我该怎么做?我的 Player
class 包含许多对 SendLog()
的调用,所以我更喜欢在开头声明 Form1
的全局实例,这样我就可以使用 f.SendLog();
而不是每次调用都将 Form1
实例传递给方法。
像这样:
class Player
{
public Form1 f = Form1;
public void Print()
{
f.SendLog();
}
}
一种方法是将Form1
class作为参数发送给播放器class。
喜欢以下内容:
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
//...................
Player player = new Player(this);
player.Show();
}
玩家Class
class Player
{
Form1 f;
public Player(Form1 _f)
{
f = _f;
}
public void Print()
{
f.SendLog();
}
}
另一种方法是使用 Application.OpenForms
获取应用程序拥有的打开表单的集合。
var form1 = Application.OpenForms.OfType<Form1>().Where(x => x.Name == "formName").FirstOrDefault();
form1.SendLog();
或使用
foreach (Form frm in Application.OpenForms)
{
if(frm.Name == "formName")
{
frm.SendLog();
break;
}
}
在我的主窗体中:
partial class Form1 : Form
我有这个方法:
public void SendLog();
另一个class里面:class Player
我有一个方法,我想从 Form1
SendLog()
public void Print()
{
Form1.SendLog(); // Error: An object reference is required for the non-static field, method, or property 'Form1.SendLog(string)'
}
我该怎么做?我的 Player
class 包含许多对 SendLog()
的调用,所以我更喜欢在开头声明 Form1
的全局实例,这样我就可以使用 f.SendLog();
而不是每次调用都将 Form1
实例传递给方法。
像这样:
class Player
{
public Form1 f = Form1;
public void Print()
{
f.SendLog();
}
}
一种方法是将Form1
class作为参数发送给播放器class。
喜欢以下内容:
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
//...................
Player player = new Player(this);
player.Show();
}
玩家Class
class Player
{
Form1 f;
public Player(Form1 _f)
{
f = _f;
}
public void Print()
{
f.SendLog();
}
}
另一种方法是使用 Application.OpenForms
获取应用程序拥有的打开表单的集合。
var form1 = Application.OpenForms.OfType<Form1>().Where(x => x.Name == "formName").FirstOrDefault();
form1.SendLog();
或使用
foreach (Form frm in Application.OpenForms)
{
if(frm.Name == "formName")
{
frm.SendLog();
break;
}
}