小编典典

反射:如何使用参数调用方法

c#

我试图通过反射与参数来调用方法,我得到:

对象与目标类型不匹配

如果我调用不带参数的方法,则效果很好。基于以下代码(如果我调用该方法)Test("TestNoParameters"),它可以正常工作。但是,如果我致电Test("Run"),我会得到一个例外。我的代码有问题吗?

我最初的目的是传递一个对象数组,例如,public void Run(object[] options)但这没有用,我尝试了一些简单的事情,例如字符串,但没有成功。

// Assembly1.dll
namespace TestAssembly
{
    public class Main
    {
        public void Run(string parameters)
        { 
            // Do something... 
        }
        public void TestNoParameters()
        {
            // Do something... 
        }
    }
}

// Executing Assembly.exe
public class TestReflection
{
    public void Test(string methodName)
    {
        Assembly assembly = Assembly.LoadFile("...Assembly1.dll");
        Type type = assembly.GetType("TestAssembly.Main");

        if (type != null)
        {
            MethodInfo methodInfo = type.GetMethod(methodName);

            if (methodInfo != null)
            {
                object result = null;
                ParameterInfo[] parameters = methodInfo.GetParameters();
                object classInstance = Activator.CreateInstance(type, null);

                if (parameters.Length == 0)
                {
                    // This works fine
                    result = methodInfo.Invoke(classInstance, null);
                }
                else
                {
                    object[] parametersArray = new object[] { "Hello" };

                    // The invoke does NOT work;
                    // it throws "Object does not match target type"             
                    result = methodInfo.Invoke(methodInfo, parametersArray);
                }
            }
        }
    }
}

阅读 488

收藏
2020-05-19

共1个答案

小编典典

就像在使用null参数数组的调用中一样,将“ methodInfo”更改为“ classInstance”。

  result = methodInfo.Invoke(classInstance, parametersArray);
2020-05-19