出於測試目的,我正在檢查引用類中的一系列方法簽名是否已在不同的靜態類上實現。對於大多數人以下工作:通用方法的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