c# - 反射(reflection):如何调用带参数的方法

标签 c# reflection parameters methods invoke

我试图通过带参数的反射调用一个方法,我得到:

object does not match target type

如果我调用一个没有参数的方法,它工作正常。基于以下代码,如果我调用方法 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);
                }
            }
        }
    }
}

最佳答案

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

  result = methodInfo.Invoke(classInstance, parametersArray);

关于c# - 反射(reflection):如何调用带参数的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2202381/

相关文章:

c# - 首先在 Entity Framework 代码中与中间对象进行多对多映射

c# - 对继承的静态属性的反射(reflection)

c# - 使用 .NET 进行 Java RSA/ECB/PKCS1Padding 加密

c# - 如何获取组合框中的项目数?

c# - IoC Windows 服务架构

reflection - 通过反射传递引用嵌套结构

.net - 从 .NET 程序集获取 ProgID

C++: "Field ' object_var'必须在基类的构造函数中初始化"

python - 如何从 Python 中的存储过程获取输出参数?

list - 带有 List 对象的 XUnit MemberData