C#无法从父类

时间:2015-06-22 04:54:29

标签: c# winforms applicationcontext

我正在尝试在类中添加一个事件处理程序,该类引用在该类中实例化的表单控件的事件。所有类都存在于同一名称空间中。

该程序基于ApplicationContext表单应用程序。在static void Main()

中的Program.cs
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)
    {
        ...
    }

    ...
}

从设计师生成的public partial class AppForm AppForm.Designer.cs内,我已经制作了控制修饰符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

2 个答案:

答案 0 :(得分:2)

编译器认为appFormForm而不是AppForm,因为您声明它的方式:

Form appForm;

尝试将声明更改为AppForm appForm;或将其转换为:

((AppForm)appForm).someToolStripMenuItem.Click += form_Click;

答案 1 :(得分:1)

问题是您的appForm字段被声明为Form类型。 Form类没有名为someToolStripMenuItem的成员。您需要将字段声明为AppForm类型才能访问该类型的成员。