Reputation: 3875
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 ?
Upvotes: 0
Views: 233
Reputation: 11487
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 } );
Upvotes: 3
Reputation: 67108
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() });
}
Upvotes: 5
Reputation: 55172
Perhaps you use the backtick notation:
Publish`1[[assemblyQualifiedNameOfTypeOfClassl]]
(Just a guess; not tested).
Upvotes: 0