2009-02-20 59 views
45

的示例代碼是我嘗試做一定會做得比我更好的英語:MethodInfo.Invoke與OUT參數

public bool IsNumericValueInBounds (string value, Type numericType) 
{ 
    double d = double.NaN;  

    bool inBounds = (bool)numericType.GetMethod ("TryParse").Invoke (null, new object[] { value, d }); 

    return inBounds; 
} 

可惜的TryParse方法需要一個輸出參數所以這是行不通的。 任何想法如何解決這個問題?

(PS:這would'nt對鴨打字很好的例子 - 因爲我知道每個numericType有一個「的TryParse」還是我看錯了?)

+0

你應該能夠分析任何數字類型加倍,所以double.TryParse()應該在這裏做? – 2009-02-20 11:49:02

+2

對於未來的人來說:@Lars,並不是每個數字都可以被解析爲雙倍而不會失去精確度,特別是「decimal」是這裏最糟糕的犯罪者。 – Crisfole 2012-03-30 14:37:35

回答

89
public static bool TryParse(string text, out int number) { .. } 

MethodInfo method = GetTryParseMethodInfo(); 
object[] parameters = new object[]{ "12345", null } 
object result = method.Invoke(null, parameters); 
bool blResult = (bool)result; 
if (blResult) { 
    int parsedNumber = (int)parameters[1]; 
}