C#Inherited Class查找基类函数

时间:2014-08-21 13:04:38

标签: c# winforms

我有一些不同的无模式表单,我最近从一个名为Popup_Base的类继承而来。基本上,这只包含一些事件和变量,我用它来从无模式窗体中获取数据,并允许我将一般的calss传递给我用来打开这些窗口的另一个帮助器类。无论如何,问题是对于从此Popup_Base继承的特定类,它会引发错误,在基类中查找顶级函数。例如,Calendar继承Popup_Base类并包含Date_Click等函数。但是,编译器抛出一个错误,说它无法找到它。像这样:

"Error  1   'Popup_Base' does not contain a definition for 'monthCalendar1_DateSelected' and no extension method 'monthCalendar1_DateSelected' accepting a first argument of type 'Popup_Base' could be found (are you missing a using directive or an assembly reference?)"

我收到类似的错误

"Error  5   'Popup_Base.InitializeComponent()' is inaccessible due to its protection level

我不会发布我的整个代码,但Popup类看起来像这样:

public partial class Popup_Base : Form
{
    public event EventHandler<NameUpdatedEventArgs> FirstNameUpdated;
    protected Control m_ctrl;
    protected virtual void OnFirstNameUpdated(NameUpdatedEventArgs e)
    {
        if (FirstNameUpdated != null)
            FirstNameUpdated(this, e);
    }

    protected int? m_row;
    protected int? m_col;

    public void Set_Sender_Info(Control Ctrl, int? Row = null, int? Col = null)
    {
        m_ctrl = Ctrl;
        m_row = Row;
        m_col = Col;
    }
}

(这些名字取自教程)

然后,这是一个样本日历

public partial class form_Calendar : Popup_Base
{
    //
    public form_Calendar(int ix, int iy, Calendar_Display_Mode Type = Calendar_Display_Mode.Day, Control Sender = null, int? row = null, int? col = null)
    {
        if (Type == Calendar_Display_Mode.Month)
            //monthCalendar1.selection
            x = ix;
        y = iy;
        //this.Location = new Point(
        InitializeComponent();
        // this.Location = new Point(x, y);

    }
}

我觉得这是非常愚蠢的事情,我很遗憾。

2 个答案:

答案 0 :(得分:1)

我想这是真的,因为您的PopupBase确实没有名为monthCalendar1_DateSelected的方法。 (最有可能在PopupBase.Designer.cs文件中预期。您必须双击monthCalendar控件并删除方法,而不是事件处理程序注册。)

如果您想要派生一个使用设计器构建的类,那么关于InitializeComponent的错误可能是正确的。 InitializeComponent private很可能是PopupBase中的protected,您必须让PopupBase工作,或者只调用{{1}}中的{{1}}方法更有意义。

答案 1 :(得分:1)

变量monthCalendar1的类型似乎是Popup_Base。并且Popup_Base对于仅出现在派生类中的方法一无所知。想象一下以下派生类:

public partial class form_Calendar : Popup_Base
{
    public void monthCalendar1_DateSelected(object sender, EventArgs e)
    {
    }
}

在这种情况下,您无法在monthCalendar1_DateSelected类型的变量上调用Popup_Base

Popup_Base popup = new form_Calendar();
popup.DateSelected += popup.monthCalendar1_DateSelected; // <-- error!

您必须在派生类型的变量上调用它:

form_Calendar calendar = new form_Calendar();
calendar.DateSelected += calendar.monthCalendar1_DateSelected; // <-- this works!

如果您只有一个Popup_Base变量,则可以转换为派生类型:

Popup_Base popup= new form_Calendar();
form_Calendar calendar = (form_Calendar)popup;
calendar.DateSelected += calendar.monthCalendar1_DateSelected; // <-- this works!