C#无法从父类访问窗体的公共成员
本文关键字:成员 窗体 访问 父类 | 更新日期: 2023-09-27 17:57:32
我正试图在一个类中添加一个事件处理程序,该类引用在该类中实例化的窗体控件的事件。所有类都存在于同一个命名空间中。
该程序基于ApplicationContext
表单应用程序。Program.cs
中的static void Main()
内
CustomApplicationContext applicationContext = new CustomApplicationContext();
Application.Run(applicationContext);
在public class 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
,并制作了类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;
问题是您的appForm
字段被声明为类型Form
。Form
类没有名为someToolStripMenuItem
的成员。您需要将字段声明为类型AppForm
才能访问该类型的成员。