C# 反射调用 - 类型“XXX"的对象无法转换为类型“System.Object[]"
我创建了一个名为 input
的实例,其类型为:
I have created an instance called input
that is of type:
public class TestInput
{
public int TesTInt { get; set; }
}
我在这个函数中使用它:
I use this in this function:
public static class TestClass
{
public static string TestFunction()
{
var testInput = new TestInput();
string res = ServicesManager.Execute<string>((object) testInput);
return res;
}
}
Execute
函数在这里:
public static OUT Execute<OUT>(object input)
where OUT : class
{
var method = //getting method by reflection
object[] arr = new object[] { input };
return method.Invoke(null, arr) as OUT; //Error is triggered here
}
我调用的方法是这个:
public static string TestFunctionProxy(object[] input)
{
var serviceInput = input[0] as TestInput;
//rest of code
}
我收到了标题中的错误.(XXX - 测试输入"类型)
I received the error in the title. (XXX - "TestInput" type)
发生了什么以及导致此错误的原因是什么?
What's happening and what is causing this error?
注意:method
是静态的,因此第一个参数不需要实例.如果我错了,请纠正我.
Note: method
is static so no instance is required for the first parameter. Please correct me if I'm wrong.
感谢任何帮助.
用一些完整示例的更多代码更新了问题.
Updated the question with some more code for a complete example.
您向方法传递了错误的参数.它想要一个 object[] 而你给的是一个 simpe 对象.这是修复它的方法:
You are passing the wrong arguments to the method. It wants an object[] and you are giving a simpe object. This is how to fix it:
object[] arr = new object[] { new object[] { input } };
'outer' 对象[] 是 Invoke 的参数,'inner' 数组是您的方法的参数.
The 'outer' object[] is the parameter for Invoke, the 'inner' array is the parameter for your method.