c# - 抛出 AmbiguousMatchException

标签 c# .net reflection

我写了这段代码:

 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/

相关文章:

C# MS Exchange 将电子邮件移动到文件夹

c# - 在不更改接口(interface)返回类型的情况下更改 WCF 中函数的返回类型

c# - 实现接口(interface)的类型的 Entity Framework DBSet 扩展

c# - 异步等待 WhenAll 不等待

c# - 在 C#4.0 中使用默认值反射(reflect)构造函数

c# - System.TypeLoadException : 'Method ' GetItem' in type 'Microsoft.AspNetCore.Mvc.Razor.Internal.FileProviderRazorProjectFileSystem' in asp. 网络核心

c# - 为什么递增 Nullable<int> 不会抛出异常?

c# - 为什么输入字符串 "**$&"上的替换模式 "$1.30"返回一个前面有 "**"且输入字符串为 "after"的字符串?

Javascript |代理| Handler.get() 方法未设置目标对象属性

C#使用反射获取不安全结构中固定字段的类型