Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/.net/24.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 引发了含糊不清的MatchException_C#_.net_Reflection - Fatal编程技术网

C# 引发了含糊不清的MatchException

C# 引发了含糊不清的MatchException,c#,.net,reflection,C#,.net,Reflection,我写了这段代码: MethodInfo method2 = typeof(IntPtr).GetMethod( "op_Explicit", BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic, null, new Type[]{ typeof(IntPtr), },

我写了这段代码:

 MethodInfo method2 = typeof(IntPtr).GetMethod(
            "op_Explicit",
            BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic,
            null,
            new Type[]{
        typeof(IntPtr),

        },
            null

            );
如果我尝试运行,我会得到一个模糊的MatchException,我如何解决这个问题?谢谢


我尝试获取的方法是op_Explicit(intptr)返回值int32

有多个显式运算符,它们允许将
intptr
作为参数,并且它们仅在返回类型上有所不同。通过不仅指定参数类型,还指定返回类型,尝试使用此问题的解决方案来获得您感兴趣的方法:


没有标准重载可用于选择不同类型的方法。你必须自己找到方法。您可以编写自己的扩展方法,如下所示:

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
进行此操作

您好,谢谢您的回答,但为什么它会给我错误提示?在哪里?它还给出了返回类型.GetMethod的错误(“op_Explicit”,BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic,新类型[]{type},returnType);在文件的开头使用System.Reflection导入System.Reflection,并
确定除此返回类型以外的所有错误。GetMethod(“op_Explicit”,BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic,new type[]{type},returnType);它表示getMethodAccept 4方法没有重载arguments@user1872492我在我的TypeExtensions中定义了这个GetMehod重载,你用过吗?哈哈。它在这里工作:。请将您的代码粘贴到某个地方(pastebin)并显示编译器错误日志