c#继承类查找基类函数
本文关键字:基类 类函数 查找 继承 | 更新日期: 2023-09-27 18:19:08
我有几个不同的非模态表单,我最近从一个类继承,我称之为Popup_Base。基本上,这只包含一些事件和变量,我用它来从非模态表单获取数据,并允许我将一个通用类传递给我用来打开这些窗口的另一个助手类。无论如何,问题是,对于继承了这个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
"
我不会张贴我的整个代码,但弹出类看起来像这样:
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
的错误可能为真。InitializeComponent
很可能是PopupBase
中的private
,您必须使其protected
工作,或者只调用PopupBase
的方法,这似乎更有意义。
变量monthCalendar1
的类型似乎是Popup_Base
。Popup_Base
对只存在于派生类中的方法一无所知。想象下面的派生类:
public partial class form_Calendar : Popup_Base
{
public void monthCalendar1_DateSelected(object sender, EventArgs e)
{
}
}
在这种情况下,不能对Popup_Base
类型的变量调用monthCalendar1_DateSelected
:
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!