繁体   English   中英

C#继承的类寻找基类函数

[英]C# Inherited Class looks for Base Class Functions

我最近从一个称为Popup_Base的类继承了几种不同的无模式形式。 基本上,这仅包含一些事件和变量,我使用这些事件和变量从无模式的形式获取数据,并允许我将常规传递给另一个我用来打开这些窗口的帮助程序类。 无论如何,问题在于对于继承自此Popup_Base的特定类,它会在查找基类中的顶级函数时引发错误。 例如,日历继承自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);

    }
}

我觉得这真是愚蠢,我错过了。

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

如果要派生使用设计器构建的类,则有关InitializeComponent的错误可能为true。 InitializeComponent很可能在PopupBaseprivate的,您必须使其protected才能工作,或者仅从PopupBase调用方法,这似乎更有意义。

变量monthCalendar1的类型似乎是Popup_Base 而且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_Base popup= new form_Calendar();
form_Calendar calendar = (form_Calendar)popup;
calendar.DateSelected += calendar.monthCalendar1_DateSelected; // <-- this works!

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM