3

私はこのコードを書きました:

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

        },
            null

            );

実行しようとすると、ambiguousmatchexception が発生します。この問題を解決するにはどうすればよいですか? ありがとう

私が取得しようとしているメソッドは op_Explicit(intptr) 戻り値 int32 です

4

2 に答える 2

2

異なる型のメソッドを選択するための標準的なオーバーロードはありません。自分で方法を見つけなければなりません。次のように、独自の拡張メソッドを作成できます。

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この目的で使用できます

于 2013-07-10T10:22:26.957 に答える
1

パラメータとして許可する複数の明示的な演算子がありIntPtr、戻り値の型のみが異なります。この質問の解決策を使用して、パラメーターの型だけでなく戻り値の型も指定して、関心のあるメソッドを取得してみてください。

Type.GetMethods() から特定の署名を持つメソッドのみを取得します

于 2013-07-10T10:09:20.997 に答える