我写了这段代码:
MethodInfo method2 = typeof(IntPtr).GetMethod(
"op_Explicit",
BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic,
null,
new Type[]{
typeof(IntPtr),
},
null
);
如果我尝试运行我得到一个不明确的匹配异常,我该如何解决这个问题?谢谢
我想获取的方法是op_Explicit(intptr)返回值int32
最佳答案
没有用于在不同类型的方法之间进行选择的标准重载。你必须自己找到方法。您可以编写自己的扩展方法,如下所示:
public static class TypeExtensions {
public static MethodInfo GetMethod(this Type type, string name, BindingFlags bindingAttr, Type[] types, Type returnType ) {
var methods = type
.GetMethods(BindingFlags.Static | BindingFlags.Public)
.Where(mi => mi.Name == "op_Explicit")
.Where(mi => mi.ReturnType == typeof(int));
if (!methods.Any())
return null;
if (methods.Count() > 1)
throw new System.Reflection.AmbiguousMatchException();
return methods.First();
}
public static MethodInfo GetExplicitCastToMethod(this Type type, Type returnType )
{
return type.GetMethod("op_Explicit", BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic, new Type[] { type }, returnType);
}
}
然后使用它:
MethodInfo m = typeof(IntPtr).GetExplicitCastToMethod(typeof(int));
准确的说,在IntPtr类中定义了两个类型转换:
public static explicit operator IntPtr(long value)
public static explicit operator long(IntPtr value)
并且在 System.Int64 类中没有定义转换(long 是 Int64 的别名)。
您可以为此目的使用Convert.ChangeType
关于c# - 抛出 AmbiguousMatchException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17567666/