C#无法从父类访问Form的公共成员

我试图在一个类中添加一个事件处理程序,以引用在该类中实例化的窗体控件的事件.所有类都存在于同一名称空间中.

该程序基于ApplicationContext窗体应用程序.在Program.cs的静态void Main()中

CustomApplicationContext applicationContext = new CustomApplicationContext();
Application.Run(applicationContext);

在公共类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中的公共局部类AppForm中,我将控件修饰符公开,并将类公开

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是公共的.

解决方法:

由于您声明的方式,编译器认为appForm是一个Form而不是一个AppForm:

Form appForm;

尝试将声明更改为AppForm appForm;或将其投射为:

((AppForm)appForm).someToolStripMenuItem.Click += form_Click;
上一篇:jdk、jre、jvm的关系


下一篇:Event对象的事件句柄