出于测试目的,我正在检查引用类中的一系列方法签名是否已在不同的静态类上实现。对于大多数人以下工作:通用方法的Type.GetMethod()
private static IEnumerable<Signature> GetMethodSigs(Type type)
{
// Get MethodInfos, filter and project into signatures
var methods = type.GetMethods(
BindingFlags.Public
| BindingFlags.DeclaredOnly
| BindingFlags.Static
| BindingFlags.Instance)
.Where(mi => !mi.Name.StartsWith("get_"))
.Where(mi => !mi.Name.StartsWith("set_"))
.Select(o => new Signature(o.Name, o.ReturnType, o.GetParameters().Select(pi => pi.ParameterType)));
return methods;
}
private static MethodInfo FindMethod(Type type, Signature sig)
{
MethodInfo member = type.GetMethod(
sig.Name,
BindingFlags.Public | BindingFlags.Static,
null,
sig.ParameterTypes.ToArray(),
null);
return member;
}
public struct Signature
{
public string Name;
public Type ReturnType;
public IEnumerable<Type> ParameterTypes;
public Signature(string name, Type returnType, IEnumerable<Type> parameterTypes = null)
{
Name = name;
ReturnType = returnType;
ParameterTypes = parameterTypes;
}
}
这是一个测试类的一部分,但是想象一下下面的代码在驾驶过程:
foreach(var sig in GetMethodSigs(typeof(ReferenceClass)))
Console.WriteLine(FindMethod(typeof(TestClass), sig)?.ToString());
以下方法签名被拾起好上ReferenceClass
,但FindMethod()
不上TestClass
找到一个等效的方法(这确实存在!):
public static void SomeMethod<T>(SomeDelegate<T> del)
GetMethods()
为我提供了一个del
参数类型(SomeDelegate`1
),但这显然不适合在GetMethod()
中搜索,因为FindMethod()
返回null
此输入。
任何想法如何操纵从GetMethods()
返回的值来搜索使用GetMethod()
(泛型参数在代表中使用,而不是简单的参数类型)的泛型方法?
(我知道有一种GetMethod()
版本只是走一个名字,但一些方法名的重载,我需要搜索参数类型为好。)
可能是这样的帮助:https://stackoverflow.com/questions/232535/how-do-i-use-reflection-to-call-a-generic-method –
@EhsanSajjad不幸的是,这些问题的答案(和其他类似的问题)假设该方法可以通过使用名称找到 - 我需要包含参数,这就是我遇到麻烦的地方。 –
与其使用类型参数调用'GetMethod',为什么不调用'GetMethods'然后遍历结果(匹配名称)并比较参数类型? – BurnsBA