2014-10-06 39 views
0

驗證一個變量,我有以下驗證類型:如何使用泛型類型

Boolean valid = Int32.TryParse(value, out result); 

如何使用的TryParse針對通用?例如:

public Boolean Validate<T>(Object value) { 
    // Get TryParse of T type and check if value is of that type. 
} 

如何驗證值以檢查它是否爲T型?

+1

如果您直到運行時纔會知道實際類型(這往往是出現此類問題時),那麼您將如何真正使用這些信息? – 2014-10-06 17:20:04

+0

我認爲你的意思是你的價值參數是字符串類型 – 2014-10-06 17:42:32

回答

1

您可以使用反射來獲取的TryParse適當的過載和調用它:

public static bool Validate<T>(string value) 
{ 
    var flags = BindingFlags.Public | BindingFlags.Static; 
    var method = typeof(T).GetMethod(
      "TryParse", 
      flags, 
      null, 
      new[] { typeof(string), typeof(T).MakeByRefType() }, 
      null); 
    if (method != null) 
    { 
     T result = default(T); 
     return (bool)method.Invoke(null, new object[] { value, result }); 
    } 
    else 
    { 
     // there is no appropriate TryParse method on T so the type is not supported 
    } 
} 

的用法是這樣的:

bool isValid = Validate<double>("12.34"); 
0

並非所有的數據類型,實現分析或tryparse方法。但是,許多類型都有一個可用於嘗試從字符串轉換的關聯TypeConverter。

public Boolean Validate<T>(string value) 
{ 
    var converter = TypeDescriptor.GetConverter(typeof(T)); 
    return converter != null ? converter.IsValid(value) : false; 
} 
+0

我不應該檢查轉換器是否存在?你說過很多類型都不是全部。 – 2014-10-06 17:42:01

+0

我添加了一個檢查,如果轉換器存在。這種技術應該能夠從字符串轉換更多的類型,而不是尋找Parse方法。另一種技術是使用System.Convert類,但是它不會覆蓋很多類型。 – 2014-10-06 17:50:07