在派生类中引发事件处理程序

时间:2015-12-23 03:33:48

标签: c# events

任何人都可以提供解决方案吗?

public class BaseOne{
    public event EventHandler OperationChanged;
}

public class Derived: BaseOne
{
    private void OnChange(){
        if(OperationChanged!=null){
            OperationChanged(this,new EventArgs());
        }
    }
}

public Class MainClass
{
    public void Main()
    {
        Derived d = new Derived();
        d.OperationChanged += OnOperationChange;
    }

    private void OnOperationChange(object sender, EventArgs e)
    {
        MessageBox("Hello I'm Called");
    }
}

我试过这样的话,你能建议更好的方法吗? 在此先感谢:)

2 个答案:

答案 0 :(得分:5)

您无法直接触发基类事件。

执行此操作的有用模式。

using System;

class Base
{
    public event EventHandler operationsChanged;
    public void OnOperationsChanged(EventArgs e)
    {
        operationsChanged(this,e);
    }
}
class Derived : Base
{
    public void OnSpecificOperationChanged()
    {
        OnOperationsChanged(EventArgs.Empty);
    }
}
class Test
{
    static void  Main()
    {
        Derived d = new Derived();
        d.operationsChanged += OnOperationsChanged;

        //invoke
        d.OnSpecificOperationChanged();

    }
    static void OnOperationsChanged(object sender, EventArgs e)
    {
        Console.WriteLine("called");
    }
}

https://msdn.microsoft.com/en-us/library/hy3sefw3.aspx

答案 1 :(得分:-1)

我找到了一个新的解决方案。简单的解决方案是将字段设为属性...

using System;

class Base
{
    public event EventHandler OperationsChanged {get; set;}
}
class Derived : Base
{
   public void OnSpecificOperationChanged()
   {
        OperationsChanged(this, EventArgs.Empty);
   }
}

class Test
{
    static void  Main()
    {
        Derived d = new Derived();
       d.OperationsChanged += OnOperationsChanged;

       //invoke
       d.OnSpecificOperationChanged();

    } 
    static void OnOperationsChanged(object sender, EventArgs e)
    {
        Console.WriteLine("called");
    }
}