反思GetMethod.选择一个更具体的方法

18 c# reflection

我想获得方法,但有一个超载.例如在对象中,我试图获得"等于".使用时

    public virtual bool Equals(object obj);
    public static bool Equals(object objA, object objB);
Run Code Online (Sandbox Code Playgroud)

写给typeof(Object).GetMethod("Equals")我一个例外,写得typeof(Object).GetMethod("public virtual bool Equals(object obj)")让我无效.在这种情况下,如何指定我想要的方法?

Jon*_*eet 30

使用其中一个允许您指定参数类型的重载.

例如:

var staticMethod = typeof(Object).GetMethod("Equals",
      BindingFlags.Static | BindingFlags.Public,
      null,
      new Type[] { typeof(object), typeof(object) },
      null);

var instanceMethod = typeof(Object).GetMethod("Equals",
      BindingFlags.Instance | BindingFlags.Public,
      null,
      new Type[] { typeof(object) },
      null);
Run Code Online (Sandbox Code Playgroud)

或者:

var staticMethod = typeof(Object).GetMethod("Equals",
      new Type[] { typeof(object), typeof(object) });

var instanceMethod = typeof(Object).GetMethod("Equals",
      new Type[] { typeof(object) });
Run Code Online (Sandbox Code Playgroud)


dev*_*ull 6

MethodInfo methodInfo = typeof(object).GetMethod("Equals", new Type[] { typeof(object), typeof(object) });
Run Code Online (Sandbox Code Playgroud)