代码之家  ›  专栏  ›  技术社区  ›  VA systems engineer

如何使用从基类继承的事件在抽象类中定义事件处理程序?

  •  2
  • VA systems engineer  · 技术社区  · 7 年前

    我的目的是重用 SelectedValueChanged 事件继承自 ComboBox 类(反过来,它从 ListControl 班级)

    在下面的代码中: 选择的值已更改 标记为屏幕截图中显示的编译器错误。我不打算 hiding 继承的事件,因此我不想使用 new 关键字。我希望从drt_comboBox_abstract派生的类能够按原样使用继承的事件。

    我如何定义 EventHandler 使用从基类继承的事件?(或者,我是否完全脱离了了解事件的轨道?)

    注意:“显示潜在修复”环绕 public event EventHandler SelectedValueChanged 具有 #pragma warning disable CS0108 这只会禁用警告。

    屏幕截图 enter image description here

    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);
            }
        }
    }
    
    1 回复  |  直到 7 年前
        1
  •  5
  •   Diego Rafael Souza    7 年前

    您不需要再次声明事件。如果它是公共的,并且在需要时已经被抛出,则可以通过订阅基类事件来处理更改(如果需要)。

    我的意思是,你可以做如下的事情:

    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
            }
        }
    }
    

    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);
            }
        }
    }
    

    注意:我已经移除了 Disable 方法只用于代码简化。这件事不在范围之内

    希望有帮助。