根据 Konrad Morawski 的回答,我创建了一个增强的扩展方法:
public static MethodInfo GetMethod (this Type i_oContainingType,
string i_sMethodName,
BindingFlags i_enBindingFlags,
Type[] i_aoArgumentType,
bool i_bGeneric)
{
if (i_oContainingType == null)
throw new ArgumentNullException (nameof (i_oContainingType));
var aoMethod = i_oContainingType.GetMethods (i_enBindingFlags);
var listoMethod = new List<MethodInfo> ();
foreach (var oMethod in aoMethod)
{
if (!string.Equals (oMethod.Name, i_sMethodName))
continue;
if (oMethod.IsGenericMethod != i_bGeneric)
continue;
var aoParameter = oMethod.GetParameters ();
if (aoParameter.Length != i_aoArgumentType?.Length)
continue;
int iParamMatch = 0;
for (int ixParam = 0; ixParam < aoParameter.Length; ixParam++)
{
if (aoParameter[ixParam].ParameterType == i_aoArgumentType[ixParam])
iParamMatch++;
}
if (iParamMatch != aoParameter.Length)
continue;
listoMethod.Add (oMethod);
}
if (listoMethod.Count != 1)
{
string sError = "Method with Name '" + i_sMethodName + "' and BindingFlags '" + i_enBindingFlags + "' and Parameter Types '" + i_aoArgumentType?.ToString ("', '") + "'";
if (listoMethod.Count == 0)
throw new MissingMethodException (sError + " has no match.");
else
throw new AmbiguousMatchException (sError + " has " + listoMethod.Count + " matches.");
}
return listoMethod[0];
}
public static MethodInfo GetPrivateInstanceMethod (this Type i_oContainingType,
string i_sMethodName,
Type[] i_aoArgumentType,
bool i_bGeneric)
{
return GetMethod (i_oContainingType, i_sMethodName, BindingFlags.NonPublic | BindingFlags.Instance, i_aoArgumentType, i_bGeneric);
}
public static MethodInfo GetPublicInstanceMethod (this Type i_oContainingType,
string i_sMethodName,
Type[] i_aoArgumentType,
bool i_bGeneric)
{
return GetMethod (i_oContainingType, i_sMethodName, BindingFlags.Public | BindingFlags.Instance, i_aoArgumentType, i_bGeneric);
}
注意:
i_aoArgumentType.ToString (..)
是另一种扩展方法。我想你可以猜到它的作用。