c# - 如何在 C# 中使用反射调用将字符串数组作为参数的方法

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

    }

由于整个框架的设置方式,我必须使用反射调用此方法。

这是我用来调用它的代码

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

这是返回 MissingMethodException 说找不到方法 Fit.TcpConnector.MakeRequest。

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

  public bool MakeRequest(string args)

代替

  public bool MakeRequest(string[] args)

然后,它就开始工作了。谁能指出我调用以数组作为参数的函数的正确方向?

最佳答案

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

所以这里发生的事情是你正在传递一个字符串数组,运行时说“啊,这是我期待的对象数组”,现在每个字符串都被作为参数传递 em>,而不是将字符串数组作为参数传递。

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

关于c# - 如何在 C# 中使用反射调用将字符串数组作为参数的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9604581/

相关文章:

c# - 仅在页面回发时插入 javascript

斯卡拉 : get mixin interfaces at runtime

c# - 获取可空类型的类型定义会破坏不可空类型的代码

php - 具有回调的唯一数组值

java - Swift iOS 类中方法和变量的数量

c# - EF Core 中的多个 Includes()

c# - 将字符串变量传递给泛型 <T>

c# - 如果场景中的多个游戏对象使用该脚本,脚本中声明的公共(public)委托(delegate)是否一定是单个实例?

c - 在C中将字符串存储在数组中

javascript - 如何在没有特定键的情况下从 JSON 对象获取值