簡體   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