Nov*_*Eng 2 c# events inheritance
我的意图是重用SelectedValueChanged从ComboBoxClass 继承的事件(反过来,继承自ListControlClass)
在下面的代码中:SelectedValueChanged标记有屏幕截图中显示的编译器错误.我不打算hiding继承事件,所以我不想使用new关键字.我希望从DRT_ComboBox_Abstract派生的类能够按原样使用继承的事件.
如何定义EventHandler使用从基类继承的事件?(或者,在理解事件方面,我完全离开这个星球吗?)
注:"显示潜在修复"包围public event EventHandler SelectedValueChanged与#pragma warning disable CS0108刚刚禁用警告.
using System;
using System.Windows.Forms;
namespace DRT
{
internal abstract partial class DRT_ComboBox_Abstract : ComboBox
{
//SelectedValueChanged is tagged with the compiler error shown in the screenshot
public event EventHandler SelectedValueChanged;
public DRT_ComboBox_Abstract()
{
InitializeComponent();
}
public void Disable()
{
this.Enabled = false;
}
public void _OnSelectedValueChanged(object sender, System.EventArgs e)
{
this.SelectedValueChanged?.Invoke(sender, e);
}
}
}
Run Code Online (Sandbox Code Playgroud)
您无需再次声明该事件.如果它是公共的并且在需要时它已被抛出,则可以通过订阅基类事件来处理所需的更改.
我的意思是,你可以这样做:
using System;
using System.Windows.Forms;
namespace DRT
{
internal abstract partial class DRT_ComboBox_Abstract : ComboBox
{
public DRT_ComboBox_Abstract()
{
InitializeComponent();
SelectedValueChanged += MyOwnHandler
}
protected virtual void MyOwnHandler(object sender, EventArgs args)
{
// Hmn.. now I know that the selection has changed and can so somethig from here
// This method is acting like a simple client
}
}
}
Run Code Online (Sandbox Code Playgroud)
在S O LID类(我相信它是这样的ComboBox),通常有效地调用订阅者来处理某些事件的方法通常是虚拟的,一旦你从这个类继承,就允许你拦截事件处理程序调用,如果这就是你想要的.
它是:
using System;
using System.Windows.Forms;
namespace DRT
{
internal abstract partial class DRT_ComboBox_Abstract : ComboBox
{
public DRT_ComboBox_Abstract()
{
InitializeComponent();
}
protected override void OnSelectedValueChanged(object sender, EventArgs args)
{
// Wait, the base class is attempting to notify the subscribers that Selected Value has Changed! Let me do something before that
// This method is intercepting the event notification
// Do stuff
// Continue throwing the notification
base.OnSelectedValueChanged(sender, args);
}
}
}
Run Code Online (Sandbox Code Playgroud)
注意:我已经删除了该Disable方法只是为了简化代码.它超出了本课题的范围
我希望它有所帮助.