views:

82

answers:

3

Context I want to make this call via reflection

instanceOfEventPublisher.Publish<T>(T eventInst);

When I call

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

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

`

I get: System.MissingMethodException: Method 'EventAggregator.EventPublisher.Publish' not found.

How to call the generic ?

A: 

Perhaps you use the backtick notation:

Publish`1[[assemblyQualifiedNameOfTypeOfClassl]]

(Just a guess; not tested).

Noon Silk
+3  A: 

You might have to do GetMethods() and search for the "Publish" MethodInfo. Or if "Publish" isn't overloaded you might get away with just GetMethod("Publish"). In either case, you'll need to call MakeGenericMethod() on the MethodInfo to add your type arguments.

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

You need to use the MakeGenericType method like such:

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

Then you can call the Publish method as you have it on the realizedType. This is true if your dealing with a Generic type; however, your code doesn't look like it is. The interface you have coming in for the eventPublisher is not a generic interface.

Can you post the rest of your code, so we can see the interface defnition and the generic class definitions.

Edit

Here's some sample code I whipped up showing how to call a method on a generic type through reflection:

  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() });

    }
JoshBerke
I've revised the formatting swallowed <T> it has to beinstanceOfEventPublisher.Publish<T>(T eventInst);
ruslander