【发布时间】: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#