2017-07-17 104 views
0

我迷路了,覺得我可能會瘋了。在下面的代碼中,TestGetCountry()工作得很好,但TestGetState()引發「參數計數不匹配」異常。我失去了爲什麼我用一種方法得到例外,但沒有其他方法。代表使用相同的簽名,傳遞相同的參數類型(字符串[])。DynamicInvoke引發參數計數不匹配

[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]; 
    } 
+1

'GetCountry'-delegate?我看到的只是一個'StringGenerators.GetStringGenerator'。 – HimBromBeere

+0

@HimBromBeere這些是被動態調用的方法。 –

+1

爲了將來的參考,值得提供[mcve]而不是零碎。 –

回答

8

string[]是轉換爲object,所以這行:

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

...用兩個參數調用委託。你想這樣的:

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

...所以它擴展到創建一個單元素object[]的唯一元素是字符串數組的引用。