通用TryParse扩展方法 [英] Generic TryParse Extension method
问题描述
从此处获取的代码
我想听听有关这种扩展方法的专家意见。我打算使用它,但是想听听我可能遇到的任何已知问题。
I would like to hear some expert opinions on this extension method. I do plan to use it, but would like to hear about any known problems i may face.
我更好地使用基本类型TryParse方法?
Am i better of using on primative types TryParse methods?
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;
}
推荐答案
TryParse
pattern最好遵循标准模式,它允许与非结构体一起使用:
The TryParse
pattern is best following the standard pattern, which allows use with non-structs, too:
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;
}
}
注意我已经接受了一个 string
这里,因为这是我最常见的意思是 TryParse
;否则, Convert.ChangeType
可能更合适。
Note I've accepted a string
here, because that is what me most commonly mean by TryParse
; otherwise, Convert.ChangeType
might be more appropriate.
我认为没有理由成为扩展方法根据问题示例中的这个
),并且肯定不适合污染对象
扩展方法太多。
I see no reason for this to be an extension method (as per this
in the question's example), and certainly it is inadvisable to pollute object
with too many extension methods.
这篇关于通用TryParse扩展方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!