有同学在 使用反射调用方法(MethodInfo.Invoke方法)进行练习时,遇到了传参报错的问题:

System.Reflection.TargetParameterCountException: Parameter count mismatch.

可能刚刚开始接触时,对 Invoke 方法传参的理解有些偏差,我们来看同学一开始的代码

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;

namespace App
{
    class Program
    {
        static void Main(string[] args)
        {
            Type type = null;
            foreach(var assembly in AppDomain.CurrentDomain.GetAssemblies())
            {
                foreach(var currentType in assembly.GetTypes())
                {
                    if(currentType.Name == "One")
                    {
                        type = currentType;
                    }
                }
            }
            // Type type = Type.GetType("App.One");   //如果非加载外部程序集,只是测试用这个简写 
            var obj = Activator.CreateInstance(type);
            MethodInfo test = type.GetMethod("Test");
            test.Invoke(obj, null);
            Console.ReadKey();
        }
    }

    class One
    {
        public void Test()
        {
            Console.WriteLine("aaaaa");
        }
    }
}

一开始想执行 One类中的 Test方法,报参数错误,后来进一步改了一下

test.Invoke(obj, null); 改成 test.Invoke(obj, new object[]{"aaaaa"});

One类修改为:

    class One
    {
        public void Test(object[] strs)
        {
            Console.WriteLine(strs[0].ToString());
        }
    }

应该是理解成 Invoke的第二个参数与 Test方法的参数要对应,还是报错!

其实正确的理解应该是:Invoke方法会将第二个参数,分折出 Test方法所需要的参数,传入到Test方法。

如果参数是这样 new object[]{"bb","cc"},Test方法应该这样写:

public void Test(string a,string b)
{
      Console.WriteLine(a);
}

如果参数是这样 new object[]{"bb",1},Test方法应该这样写:

public void Test(string a,int b)
{
     Console.WriteLine(b);
}

把上面的代码练习一下,应该就正确理解了。