1

当我有以下示例代码时:

namespace Test {
 public delegate void TestDelegate(object sender, MyEventArgs e);

 public class A {
  public event EventHandler<MyEventArgs> Handler;

  public void Test(){
   Handler += B.Observe;
  }
 }
}

public class B {
 public void Observe(TestDelegate) {
  // Do something
 }
}

我得到错误

“观察”没有重载匹配委托“System.EventHandler”

但是,当我使用

Observer(object sender, MyEventArgs e){}

它工作得很好。据我了解,委托可用于在多个地方定义方法签名,这种情况下有什么问题?

4

2 回答 2

1

方法的签名与方法Observer的签名不匹配EventHandler

(EventHandler 是 System 命名空间下的 .NET 委托类型)

你可以这样做:

public event TestDelegate Handler; 

代替

public event EventHandler<MyEventArgs> Handler; //Notice the type of Handler. Its of type EventHandler defined under System namespace.
于 2013-10-01T08:52:27.597 回答
1

委托定义签名:

public delegate void TestDelegate(object sender, MyEventArgs e);

public event TestDelegate MyEvent;

事件的处理程序必须具有与委托相同的签名:

MyEvent += MyEventHandler;

void X_Sample_MyEvent(object sender, MyEventArgs e)
{
    ...
}

你可以传递你想要的任何类型:

public delegate void AnotherDelegate();
public delegate void TestDelegate(AnotherDelegate arg);

MyEvent += X_Sample_MyEvent;

void X_Sample_MyEvent(AnotherDelegate arg) { }

或者可能是这样的:

public delegate void TestDelegate(object sender, MyEventArgs e);

MyEvent += (sender, e) =>
{
    Observe(MyEvent);
};

void Observe(TestDelegate arg)
{
}
于 2013-10-01T08:56:21.347 回答