我试图在运行时调用一个通用接口方法,但是在查找类型信息时似乎找到了 IDomainEventSubscriber 而不是传递的正确类型。
抛出运行时错误:Object does not match target type.
检查我看到的 handlerInstance 类型的值是typeof(TestEventHandler)
,并methodInfo{System.Reflection.MethodBase}
显示{Void HandleEvent(System.Object)}
。
所以它被设置为 System.Object 的方法类型,而不是实际类型(例如,在我们调用的情况下为 TestEvent Dispatch(new TestEvent());
)
是否有可能获得正确的实现,以便我可以在运行时调用接口成员?
public interface IDomainEventSubscriber<T>
{
void HandleEvent(T domainEvent);
}
class TestEventHandler : IDomainEventSubscriber<TestEvent>
{
public void HandleEvent(TestEvent domainEvent)
{
}
}
// some service that dispatches events
void Dispatch<T>(T eventToPublish) where T : class
{
Type handlerType = map.GetHandlersForType(eventToPublish.GetType());
// a valid object instance is returned from my IoC container
object handlerInstance = this.ResolveHandler<T>(handlerType);
// i can guarantee the instance implements IDomainEventSubscriber<T> where T
// is the same type as eventToPublish
Type typeInfo = typeof(IDomainEventSubscriber<T>);
MethodInfo methodInfo = typeInfo.GetMethod("HandleEvent");
// this line throws an error :(
methodInfo.Invoke(handlerInstance, new object[] { eventToPublish });
}