I was wondering if someone might be able to demonstrate how to use Type's GetMethod() method to retrieve a MethodInfo object for the following signature:
Class.StaticMethod<T>(T arg1, IInterface1 arg2, IEnumerable<IInterface2> arg3)
Thanks,
Xam
An element of typeArguments does not satisfy the constraints specified for the corresponding type parameter of the current generic method definition. This method is not supported. The following code example demonstrates the properties and methods of MethodInfo that support the examination of generic methods. The example does the following:
The type parameter section of a generic class can have one or more type parameters separated by commas. We can write a single generic method declaration that can be called with arguments of different types. Based on the types of arguments passed to the generic method, the compiler handles each method call appropriately.
Where genericmethod < Object > is the name of the method to call and any type that satisfies the general constraint. (Action) matches the signature of the method to be called, that is, (func < string, string, int > or Action < bool >) Method 1: use GetMethod () or GetMethods () with the appropriate type or binding flags.
Following are the rules to define Generic Methods All generic method declarations have a type parameter section indicated by angle brackets <> that precedes the method’s return type. Each type parameter section can contain one or more type parameters separated by commas.
MethodInfo methodInfo = typeof(Class)
.GetMethods(
BindingFlags.Public | BindingFlags.Static
)
.Where(m => m.Name == "StaticMethod")
.Where(m => m.IsGenericMethod)
.Where(m => m.GetGenericArguments().Length == 1)
.Where(m => m.GetParameters().Length == 3)
.Where(m =>
m.GetParameters()[0].ParameterType ==
m.GetGenericArguments()[0] &&
m.GetParameters()[1].ParameterType ==
typeof(IInterface1) &&
m.GetParameters()[2].ParameterType ==
typeof(IEnumerable<IInterface2>)
)
.Single();
Note that you must then follow this with
methodInfo = methodInfo.MakeGenericMethod(new Type[] { typeof(ConcreteType) });
to close the type where ConcreteType
is the type you want for the type parameter T
.
I'm assuming:
class Class {
public static void StaticMethod<T>(
T arg1,
IInterface1 arg2,
IEnumerable<IInterface2> arg3
) { }
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With