任何人都可以提供解决方案吗?
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");
}
}
我试过这样的话,你能建议更好的方法吗? 在此先感谢:)
答案 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");
}
}
答案 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");
}
}