我試圖創(chuàng)建一個通用擴(kuò)展,使用'TryParse'檢查字符串是否為給定類型:public static bool Is<T>(this string input){ T notUsed; return T.TryParse(input, out notUsed);}由于無法解析符號“ TryParse”,因此無法編譯據(jù)我了解,“ TryParse”不是任何接口的一部分。這有可能嗎?更新:使用下面的答案,我想出了:public static bool Is<T>(this string input){ try { TypeDescriptor.GetConverter(typeof(T)).ConvertFromString(input); } catch { return false; } return true;}它工作得很好,但是我認(rèn)為以這種方式使用異常對我來說不合適。更新2:修改為傳遞類型,而不是使用泛型:public static bool Is(this string input, Type targetType){ try { TypeDescriptor.GetConverter(targetType).ConvertFromString(input); return true; } catch { return false; }}
3 回答

LEATH
TA貢獻(xiàn)1936條經(jīng)驗 獲得超7個贊
使用try / catches進(jìn)行流控制是一個糟糕的策略。拋出異常會導(dǎo)致性能下降,而運行時會解決該異常。而是在轉(zhuǎn)換之前驗證數(shù)據(jù)。
var attemptedValue = "asdfasdsd";
var type = typeof(int);
var converter = TypeDescriptor.GetConverter(type);
if (converter != null && converter.IsValid(attemptedValue))
return converter.ConvertFromString(attemptedValue);
else
return Activator.CreateInstance(type);
- 3 回答
- 0 關(guān)注
- 416 瀏覽
添加回答
舉報
0/150
提交
取消