Reputation: 592
Assuming that I have a third party class Foo with a signature like this:
void Execute<T>();
void Execute(string[] args);
Instead of calling
Execute<Bar>();
I need to use the qualified name of the Bar classe to invoke the generic method. Example:
Type barType = Type.GetType("Program.Bar");
Execute<barType>();
I've already tried some answers I found on other threads but all of them gave me issues. For instance, I can't use the GetMethod("Execute") since it throws an ambiguous excpetion.
Upvotes: 1
Views: 226
Reputation: 27357
You can run it like this:
class A
{
public void Execute<T>() { }
public void Execute(string[] args) { }
}
var method = typeof(A).GetMethods().FirstOrDefault(
m => m.Name == "Execute"
&& !m.GetParameters().Any()
&& m.GetGenericArguments().Count() == 1
);
Type barType = Type.GetType("Program.Bar");
method.MakeGenericMethod(barType).Invoke();
You can either change FirstOrDefault
to First
, or add some error handling if null
is expected (depends on your use case).
Upvotes: 1
Reputation: 1643
Type parameters have to be known at compile time, so in order to call the method directly, you will need to either wrap the type or change the signature to take in a type.
Otherwise, you will need to use reflection to invoke the method by name.
Upvotes: 0