I have a MethodInfo passed in to a function and I want to do the following
MethodInfo containsMethod = typeof(ICollection<>).GetMethod("Contains");
if (methodInfo.Equals(containsMethod)
{
// do something
}
But this doesn't work because the methodInfo has a specific generic type. For the example does work if I knew that the ICollection was always of type string.
MethodInfo containsMethod = typeof(ICollection<string>).GetMethod("Contains");
if (methodInfo.Equals(containsMethod)
{
// do something
}
How can I check whether the MethodInfo is a ANY typed instance of the generic method without caring what the type is?
Thanks.
EDIT: Question clarification
As correctly pointed out the method is not generic but the containing class is so the question is more how to I find out if the MethodInfo is for a Type which is a typed instance of ICollection<>.
EDIT: more context
I am writing a Linq provider and trying to handle the "in" case
IList<string> myList = new List<string>{ "1", "2" };
from Something s in ...
where myList.Contains(s.name)
select s;
Generic methods are methods that introduce their own type parameters. This is similar to declaring a generic type, but the type parameter's scope is limited to the method where it is declared. Static and non-static generic methods are allowed, as well as generic class constructors.
From the point of view of reflection, the difference between a generic type and an ordinary type is that a generic type has associated with it a set of type parameters (if it is a generic type definition) or type arguments (if it is a constructed type). A generic method differs from an ordinary method in the same way.
Which of the following allows us to call generic methods as a normal method? Explanation: Type inference, allows you to invoke a generic method as an ordinary method, without specifying a type between angle brackets.
Yes, you can define a generic method in a non-generic class in Java.
Note that ICollection<T>.Contains
is not a generic method - it is a non-generic method of a generic type. Otherwise IsGenericMethod
and GetGenericTypeDefinition
would help. You could obtain the generic type definition (DeclaringType.GetGenericTypeDefinition()
) and work back up to Contains
, but I wonder if you are approaching this problem the hard way.
Usually, if you are using reflection, it may be pragmatic to drop to non-generic IList
- unless you need the type data (for example, for meta-programming). And in that case, I would consider looking closely to see if you can simplify the setup here.
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