C# Reflection Invoke - Object of Type 'XXX' Cannot Be Converted to type 'System.Object[]'

不问归期 提交于 2019-12-25 02:44:08

问题


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;
    }
}

The Execute function is here:

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
}

The method that I invoke is this one:

public static string TestFunctionProxy(object[] input)
{
       var serviceInput = input[0] as TestInput;
       //rest of code
}

I received the error in the title. (XXX - "TestInput" type)

What's happening and what is causing this error?

Note: method is static so no instance is required for the first parameter. Please correct me if I'm wrong.

Any help is appreciated.

EDIT: Updated the question with some more code for a complete example.


回答1:


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 } };

The 'outer' object[] is the parameter for Invoke, the 'inner' array is the parameter for your method.



来源:https://stackoverflow.com/questions/21855840/c-sharp-reflection-invoke-object-of-type-xxx-cannot-be-converted-to-type-sy

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!