如何使用反射获得重载的私有/受保护方法

Rag*_*v55 12 c# reflection

using System;
using System.Reflection;

namespace Reflection        
{
    class Test
    {
        protected void methodname(int i)
        {
            Console.WriteLine(("in the world of the reflection- only i"));
            Console.Read();
        }    
        protected void methodname(int i, int j)
        {
            Console.WriteLine(("in the world of the reflection  i , j"));
            Console.Read();
        }
    }
    class Program
    {
        static void Main(string[] args)
        {
           // BindingFlags eFlags = BindingFlags.Default | BindingFlags.Instance | BindingFlags.Public|BindingFlags.NonPublic;
            BindingFlags eFlags = BindingFlags.Instance|BindingFlags.NonPublic;
            Test aTest = new Test();
            MethodInfo mInfoMethod = typeof(Reflection.Test).GetMethod("methodname", eFlags);
            mInfoMethod.Invoke(aTest, new object[] { 10 ,20});   
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

我想调用两个Getmethod()重载方法.如果我给出方法名称,则抛出运行时错误(ambigous方法调用).如何避免这种情况以及如何调用每种方法.

Abd*_*nim 22

您必须传递重载方法的类型,这是反射在出现过载时对您所需方法进行排序的方式.

您不能同时调用这两个方法,因为它具有不同类型的输入参数.您必须确切地知道您确切要调用哪一个,并传递一个Type[],例如:

// invoking overload with two parameters
MethodInfo mInfoMethod =
    typeof(Reflection.Test).GetMethod(
        "methodname",
        BindingFlags.Instance | BindingFlags.NonPublic,
        Type.DefaultBinder,
        new[] {typeof (int), typeof (int)},
        null);

mInfoMethod.Invoke(aTest, new object[] { 10 ,20});
Run Code Online (Sandbox Code Playgroud)

要么

// invoking overload with one parameters
MethodInfo mInfoMethod =
    typeof(Reflection.Test).GetMethod(
        "methodname",
        vBindingFlags.Instance | BindingFlags.NonPublic,
        Type.DefaultBinder,
        new[] { typeof (int) },
        null);

mInfoMethod.Invoke(aTest, new object[] { 10 });
Run Code Online (Sandbox Code Playgroud)


Kev*_*sse 5

使用'GetMethods'来检索所有重载,然后选择你想要的重载.