Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AmbiguousMatchException thrown

i wrote this code:

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

        },
            null

            );

if I try to run i get an ambiguousmatchexception, how can i solve this problem? thanks

The method i am trying to get is op_Explicit(intptr) return value int32

like image 834
user1872492 Avatar asked Dec 07 '25 09:12

user1872492


2 Answers

There are no standart overloads for choosing between methods with different types. You must find method by yourself. You can write your own extension methods, like this:

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);
    }
}

And then use it:

MethodInfo m = typeof(IntPtr).GetExplicitCastToMethod(typeof(int));

Be accurately, there are two defined casts in IntPtr class:

public static explicit operator IntPtr(long value)
public static explicit operator long(IntPtr value)

And no defined casts in System.Int64 class (long is alias of Int64).

You can use Convert.ChangeType for this purposes

like image 120
Viktor Lova Avatar answered Dec 09 '25 23:12

Viktor Lova


There are multiple explicit operators which allow IntPtr as a parameter and they differ only with their return types. Try to use the solution from this question to get the method which you're interested in by specifying not only parameter types but also return type:

Get only Methods with specific signature out of Type.GetMethods()

like image 37
Marek Musielak Avatar answered Dec 09 '25 23:12

Marek Musielak



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!