如何进行泛型方法调用?

时间:2009-09-17 14:19:45

标签: c# generics reflection

上下文  我想通过反思来发起这个电话

instanceOfEventPublisher.Publish<T>(T eventInst);

当我打电话

` private void GenCall(IEventPublisher eventPublisher,object theEventObj){

        var thePublisher = eventPublisher.GetType();
        thePublisher.InvokeMember(
            "Publish",
            BindingFlags.Default | BindingFlags.InvokeMethod,
            null,
            eventPublisher,
            new object[] {theEventObj}
            );
    }

`

我得到: System.MissingMethodException:找不到方法'EventAggregator.EventPublisher.Publish'。

如何调用泛型?

3 个答案:

答案 0 :(得分:5)

您需要使用MakeGenericType方法,如:

var realizedType = thePublisher.MakeGenericType(eventObj.GetType());

然后,您可以在realizeType上调用Publish方法。如果您处理Generic类型,则情况确实如此;但是,您的代码看起来并不像。您为eventPublisher加入的接口不是通用接口。

您可以发布其余的代码,因此我们可以看到接口定义和泛型类定义。

修改

这里有一些示例代码,我展示了如何通过反射调用泛型类型的方法:

  public class Publisher<T>
    {
        public void Publish(T args)
        {
            Console.WriteLine("Hello");
        }
    }
    static void Main(string[] args)
    {

        var type = typeof(Publisher<>);

        Publisher<EventArgs> publisher = new Publisher<EventArgs>();

        var realizedType = type.MakeGenericType(typeof(EventArgs));
        realizedType.InvokeMember("Publish", BindingFlags.Default | BindingFlags.InvokeMethod,
        null,
        publisher
        ,
        new object[] { new EventArgs() });

    }

答案 1 :(得分:3)

您可能必须GetMethods()并搜索“发布”MethodInfo。或者,如果“发布”没有超载,您可能只会GetMethod("Publish")。在任何一种情况下,您都需要在MakeGenericMethod()上调用MethodInfo来添加您的类型参数。

MethodInfo constructedPublish = thePublisher.GetMethod("Publish")
    .MakeGenericMethod( theEventObject.GetType() );
constructedPublish.Invoke( eventPublisher, new object[] { theEventObject } );

答案 2 :(得分:0)

也许你使用反引号表示法:

Publish`1[[assemblyQualifiedNameOfTypeOfClassl]]

(只是猜测;未经测试)。