C# 查找具有不同名称的相同函数签名
给定一个对象和一个实例方法,我想得到一个具有完全相同签名但具有不同已知名称的方法。这包括参数列表、通用参数,如果它们是签名的一部分,则可能包括属性。我该怎么做C# 查找具有不同名称的相同函数签名,c#,reflection,C#,Reflection,给定一个对象和一个实例方法,我想得到一个具有完全相同签名但具有不同已知名称的方法。这包括参数列表、通用参数,如果它们是签名的一部分,则可能包括属性。我该怎么做 我知道存在GetMethod(),但我无法确定哪个重载覆盖了所有可能的签名变体。在某些情况下,类似的情况可能会起作用: public static bool HasSameSignature(MethodInfo m1, MethodInfo m2) { if (m1.GetGenericArguments().Length != m
我知道存在
GetMethod()
,但我无法确定哪个重载覆盖了所有可能的签名变体。在某些情况下,类似的情况可能会起作用:
public static bool HasSameSignature(MethodInfo m1, MethodInfo m2)
{
if (m1.GetGenericArguments().Length != m2.GetGenericArguments().Length)
return false;
var args1 = m1.GetParameters();
var args2 = m2.GetParameters();
if (args1.Length != args2.Length)
return false;
for (var idx = 0; idx < args1.Length; idx++)
{
if (!AreEquivalentTypes(args1[idx].ParameterType, args2[idx].ParameterType))
return false;
}
return true;
}
static bool AreEquivalentTypes(Type t1, Type t2)
{
if (t1 == null || t2 == null)
return false;
if (t1 == t2)
return true;
if (t1.DeclaringMethod != null && t2.DeclaringMethod != null && t1.GenericParameterPosition == t2.GenericParameterPosition)
return true;
if (AreEquivalentTypes(t1.GetElementType(), t2.GetElementType()))
return true;
if (t1.IsGenericType && t2.IsGenericType && t1.GetGenericTypeDefinition() == t2.GetGenericTypeDefinition())
{
var ta1 = t1.GenericTypeArguments;
var ta2 = t2.GenericTypeArguments;
for (var idx = 0; idx < ta1.Length; idx++)
{
if (!AreEquivalentTypes(ta1[idx], ta2[idx]))
return false;
}
return true;
}
return false;
}
因为您包含了
reflection
标记——您希望在运行时做这个决定吗?GetMethod
的重载不会这样做,因为它们都使用一个名称。您需要GetMethods
(复数)并过滤结果。@Marathon55我也不介意在编译时这样做,但我需要在代码中使用此方法,因此使用外部工具在程序集中查找它是不够的。不具体,但这与您没有(当前)方法这一事实有关在呼叫站点指示您想要哪一个的方法。不确定它是否回答了您真正的问题,但使用给定:typegiventype=。。。;MethodInfo givenMethod=。。。;字符串givenDifferentName=代码>您可以使用类似于var desiredMethod=givenType.GetMethod(givenDifferentName,Array.ConvertAll(givenMethod.GetParameters(),pi=>pi.ParameterType))代码>。但是,如果某些参数的类型是由每个泛型方法定义的泛型参数,则它将不起作用。另外,我怀疑您认为<代码>空白NAMEONE(TX)和<代码>无效NATMITWO(S Y)< /代码>具有相同的签名吗?
Type givenType = ...;
MethodInfo givenMethod = ...;
string givenDifferentName = ...;
var answer = givenType.GetMethods()
.SingleOrDefault(m => m.Name == givenDifferentName && HasSameSignature(m, givenMethod));