我正在尝试在类中添加一个事件处理程序,该事件处理程序引用在该类中实例化的表单控件的事件。所有类都存在于同一个命名空间中。
该程序基于 ApplicationContext
表单应用程序。在 Program.cs
static void Main()
中
CustomApplicationContext applicationContext = new CustomApplicationContext();
Application.Run(applicationContext);
在 公共(public)类 CustomApplicationContext
中
public class CustomApplicationContext : ApplicationContext
{
//create the application form
Form appForm;
public CustomApplicationContext()
{
InitializeContext();
//create instance of appForm
appForm = new AppForm();
//subscribe event handler to form closing event
appForm.FormClosing += form_FormClosing; //this works fine
//subscribe event handler to form control click event
appForm.someToolStripMenuItem.Click += form_Click; //doesn't compile
//can't even find appForm.someToolStripmenuItem in code completion!
}
void form_FormClosing(object sender, FormClosingEventArgs e)
{
...
}
void form_Click(object sender, EventArgs e)
{
...
}
...
}
并且在 AppForm.Designer.cs
中的 public partial class AppForm
中,它由设计器生成,我在其中设置了控制修饰符 public
并且我已经将类(class)设置为public
public partial class AppForm //note that I made this public
{
...
this.someToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
...
//
// someToolStripMenuItem
//
this.someToolStripMenuItem.Name = "someToolStripMenuItem";
this.someToolStripMenuItem.Size = new System.Drawing.Size(178, 22);
this.someToolStripMenuItem.Text = "Some Item";
...
public System.Windows.Forms.ToolStripMenuItem someToolStripMenuItem;
}
我究竟做错了什么?当我键入 appForm.
时,someToolStripMenuItem
甚至没有出现在代码完成框中,就好像它在上下文中不可访问一样 - 但是 appForm
是可访问的,并且 someToolStripMenuItem
是 public
。
最佳答案
编译器认为 appForm
是一个 Form
而不是 AppForm
因为你声明它的方式:
Form appForm;
尝试将声明更改为 AppForm appForm;
或将其转换为:
((AppForm)appForm).someToolStripMenuItem.Click += form_Click;
关于C# 无法从父类访问 Form 的公共(public)成员,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30972329/