【问题标题】:DynamicInvoke throws Parameter count mismatch [duplicate]DynamicInvoke 引发参数计数不匹配 [重复]
【发布时间】:2017-07-17 16:07:17
【问题描述】:

我迷路了,觉得我可能要疯了。在下面的代码中,TestGetCountry() 可以正常工作,但 TestGetState() 会引发“参数计数不匹配”异常。我不知道为什么我在一种方法中得到异常,而在另一种方法中却没有。委托使用相同的签名,传递相同的参数类型(字符串 [])。

    [TestMethod]
    public void TestGetCountry()
    {
        string expected = Address.GetCountry();

        // get the method associated with this Enums.StringGenerator from the dictionary
        Delegate action = StringGenerators.GetStringGenerator(Enums.StringGenerators.COUNTRY);
        string[] args = new string[] { "" };
        string actual = (string)action.DynamicInvoke(args);

        Assert.AreEqual(expected, actual, "Country does not match");
    }

    [TestMethod]
    public void TestGetState()
    {
        string expected = "CA";

        Delegate action = StringGenerators.GetStringGenerator(Enums.StringGenerators.STATE);
        string[] args = new string[] {"CA", "NY"};
        string actual = (string)action.DynamicInvoke(args); // exception thrown here

        Assert.AreEqual(expected, actual, "State does not match");
    }

StringGenerator 委托如下所示:

public delegate string StringGenerator(object container);

GetCountry 方法如下所示:

    public static string GetCountry(object container)
    {
        return Address.GetCountry();
    }

GetState 方法如下所示:

    public static string GetState(object container)
    {
        string[] states = (string[])container;
        int index = SeedGovernor.GetRandomInt(states.Length);
        return states[index];
    }

【问题讨论】:

  • GetCountry-delegate?我看到的只是StringGenerators.GetStringGenerator。
  • @HimBromBeere 这些是动态调用的方法。
  • 为了将来参考,值得提供minimal reproducible example而不是零碎的东西。

标签: c#


【解决方案1】:

string[] 可以转换为object,所以这一行:

string actual = (string) action.DynamicInvoke(args);

... 使用两个参数调用委托。你想要这个:

string actual = (string) action.DynamicInvoke((object) args);

... 以便它展开以创建单个元素 object[],其唯一元素是对字符串数组的引用。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-02-14
    • 2017-11-17
    • 1970-01-01
    • 2011-02-10
    • 1970-01-01
    • 2017-12-31
    相关资源
    最近更新 更多