異なる型のメソッドを選択するための標準的なオーバーロードはありません。自分で方法を見つけなければなりません。次のように、独自の拡張メソッドを作成できます。
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 クラスには 2 つのキャストが定義されています。
public static explicit operator IntPtr(long value)
public static explicit operator long(IntPtr value)
また、System.Int64 クラスにはキャストが定義されていません (long は Int64 のエイリアスです)。
Convert.ChangeType
この目的で使用できます