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
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
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()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With