Mik*_*e Q 7 c# generics reflection methods equals
我有一个MethodInfo传入一个函数,我想做以下
MethodInfo containsMethod = typeof(ICollection<>).GetMethod("Contains");
if (methodInfo.Equals(containsMethod)
{
// do something
}
Run Code Online (Sandbox Code Playgroud)
但这不起作用,因为methodInfo具有特定的泛型类型.如果我知道ICollection始终是字符串类型,那么该示例确实有效.
MethodInfo containsMethod = typeof(ICollection<string>).GetMethod("Contains");
if (methodInfo.Equals(containsMethod)
{
// do something
}
Run Code Online (Sandbox Code Playgroud)
如何检查MethodInfo是否是泛型方法的任何类型实例,而不关心类型是什么?
谢谢.
编辑:问题澄清
正确地指出这个方法不是通用的,但是包含类的问题更多的是我如何找出MethodInfo是否适用于作为ICollection <>的类型化实例的Type.
编辑:更多背景
我正在写一个Linq提供程序并试图处理"in"情况
IList<string> myList = new List<string>{ "1", "2" };
from Something s in ...
where myList.Contains(s.name)
select s;
Run Code Online (Sandbox Code Playgroud)
您可以检查声明类型:
if( methodInfo.Name == "Contains"
&& methodInfo.DeclaringType.IsGenericType
&& methodInfo.DeclaringType.GetGenericTypeDefinition() == typeof(ICollection<>))
{
Run Code Online (Sandbox Code Playgroud)