定义为方法签名的委托不是有效替代

时间:2013-10-01 08:47:53

标签: c# delegates

当我有以下示例代码时:

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

我收到错误

  

'Observe'没有重载匹配委托   'System.EventHandler'

然而,当我使用

Observer(object sender, MyEventArgs e){}

它运作得很好。我的理解是委托可以用来在多个地方定义方法签名,这个场景中的问题是什么?

2 个答案:

答案 0 :(得分: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.

答案 1 :(得分:1)

delegate定义签名:

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