代码来自这里
我想听听一些关于这种扩展方法的专家意见.我打算使用它,但想知道我可能遇到的任何已知问题.
我更喜欢在主要类型上使用TryParse方法吗?
public static T? TryParse<T>(this object obj) where T : struct
{
if (obj == null) return null;
T? result = null;
TypeConverter converter = TypeDescriptor.GetConverter(typeof(T));
if (converter != null)
{
try
{
string str = obj.ToString();
result = (T)converter.ConvertFromString(str);
}
catch (Exception ex)
{
throw ex;
}
}
return result;
}
Run Code Online (Sandbox Code Playgroud)
Mar*_*ell 26
该TryParse模式最好遵循标准模式,允许与非结构一起使用:
public static bool TryParse<T>(string s, out T value) {
TypeConverter converter = TypeDescriptor.GetConverter(typeof(T));
try {
value = (T) converter.ConvertFromString(s);
return true;
} catch {
value = default(T);
return false;
}
}
Run Code Online (Sandbox Code Playgroud)
注意我在string这里接受了一个,因为这是我最常用的意思TryParse; 否则,Convert.ChangeType可能更合适.
我认为没有理由将其作为扩展方法(如this问题示例中所示),当然也不宜object使用过多的扩展方法进行污染.
| 归档时间: |
|
| 查看次数: |
6245 次 |
| 最近记录: |