2

クラスが一連のイベントを提供するイベントベースのシステムを作成し、そのメンバーメソッドを持つ別のクラスをイベントハンドラーとして最初のクラスにアタッチできます...私はただこのようなことをしたいだけです

if(isMethodCompatibleToEvent(...))
{
    connectMethodToEvent(...)
}

リフレクションを介して、これは接続が行われる方法です:

void connectMethodToEvent(object methodTarget, MethodInfo mi,
    object eventTarget, EventInfo ei)
{
    Delegate handler = Delegate.CreateDelegate(ei.EventHandlerType, methodTarget, mi);
    ei.AddEventHandler(eventTarget, handler);
}

メソッドがイベントと互換性がない場合、例外がスローされます。これを修正するために、メソッド デリゲートを作成する前にいくつかのチェックを作成したいのですが、どうすればよいでしょうか?

bool isMethodCompatibleToEvent(object methodTarget, MethodInfo mi,
    object eventTarget, EventInfo ei)
{
    // HOW ?
}
4

2 に答える 2

2
  • The number of formal parameters must be the same.
  • The "refness" of the formal parameters must be the same. (Technically a method with an out parameter may be used for an event with a ref parameter and vice versa but I don't recommend it.)
  • Each formal parameter type must be compatible. For value types they must match exactly. For formal parameters of reference type, contravariance is permitted. That is, if you have an event handler that is going to pass a Giraffe to the delegate, the delegate is permitted to take Animal.
  • The "voidness" of the return type must be the same; void only matches void.
  • For non-void return types, value types must match exactly. For event handlers that return reference types, covariance is permitted. That is, if the event handler says that it returns Animal and the delegate returns Giraffe, that's fine.

These are not all the rules but they are enough to deal with the vast majority of common cases.

于 2013-06-02T16:32:27.177 に答える