如何使用Reflection来调用一个在C#中将字符串数组作为参数的方法

Bud*_*dha 2 c# arrays reflection parameters system.reflection

我有一个如下所示的方法......

public bool MakeRequest(string[] args)
    {
        try
        {
            sXmlRequest = args[0];
            sResponse = "";
            Console.WriteLine(sXmlRequest);
            sw.Write(sXmlRequest);
            sw.Flush();
            sResponse = sr.ReadToEnd();
            return true;
        }
        catch (Exception e)
        {
            sResponse = e.Message;
            return false;
        }

    }
Run Code Online (Sandbox Code Playgroud)

我必须使用Reflection调用此方法,因为整个框架的设置方式.

这是我用来调用它的代码

string[] innerargs = {"Dummy Args"};
string pAssembly = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location) + "\\TCPConnector.dll";
Assembly assemblyInstance = Assembly.LoadFrom(pAssembly);
Type tConnector = assemblyInstance.GetType("Fit.TcpConnector");
Object oLateBound = assemblyInstance.CreateInstance(tConnector.FullName);

result = tConnector.InvokeMember("MakeRequest", BindingFlags.Public | BindingFlags.InvokeMethod | BindingFlags.Instance, null, oLateBound, innerargs);
Run Code Online (Sandbox Code Playgroud)

这将返回MissingMethodException,表示找不到方法Fit.TcpConnector.MakeRequest.

但是,如果我将MakeRequest的签名更改为

  public bool MakeRequest(string args)
Run Code Online (Sandbox Code Playgroud)

代替

  public bool MakeRequest(string[] args)
Run Code Online (Sandbox Code Playgroud)

那么,它正在发挥作用.任何人都可以在调用以数组为参数的函数时指向正确的方向吗?

Eri*_*ert 6

C#支持数组类型为引用类型的数组上的数组元素类型协方差.也就是说,您可以自动转换string[]object[].

所以这里发生的是你传递一个字符串数组,运行时说"啊,那是我期待的对象数组",现在每个字符串都作为参数传递,而不是传递字符串数组作为一个论点.

诀窍是创建一个包含字符串数组的对象数组,而不是一个字符串数组相同的对象数组.


svi*_*ick 5

你必须传递一个包含你的数组的数组:

tConnector.InvokeMember(
    "MakeRequest",
    BindingFlags.Public | BindingFlags.InvokeMethod | BindingFlags.Instance,
    null, oLateBound, new object[] { innerargs });
Run Code Online (Sandbox Code Playgroud)

这是因为传递给方法的数组中的每个项代表函数的一个参数.由于你的函数有一个类型的参数string[],你需要给它一个包含一个类型项的数组string[].

话虽如此,我认为使用GetMethod()并且Invoke()InvokeMember()以下更清楚:

var makeRequestMethod = tConnector.GetMethod("MakeRequest");
makeRequestMethod.Invoke(oLateBound, new object[] { innerargs });
Run Code Online (Sandbox Code Playgroud)

由于Eric Lippert在他的回答中指出的数组协方差,你的错误代码编译.