通用的TryParse扩展方法 [英] Generic TryParse Extension method
问题描述
代码从这里采取
我想听听这个扩展方法,一些专家的意见。我不打算使用它,但是想听到任何已知的问题,我可能会面对的问题。
我现在在灵长类动物的类型更好的使用的TryParse方法呢?
公共静态T' &的TryParse LT; T>(这个obj对象),其中T:结构
{
如果(OBJ == NULL)返回NULL;
T'结果= NULL;
类型转换器转换器= TypeDescriptor.GetConverter(typeof运算(T));
如果(变频器!= NULL)
{
试
{
字符串str = obj.ToString();
结果=(T)converter.ConvertFromString(STR);
}
赶上(异常前)
{
罚球前;
}
}
返回结果;
}
的的TryParse
模式是最好按照标准模式,该模式允许与非结构用,太:
公共静态布尔的TryParse< T>(字符串s,出的T值){
类型转换器转换器= TypeDescriptor.GetConverter(typeof运算(T));
尝试{
值=(T)converter.ConvertFromString(S);
返回真;
} {赶上
值=默认(T);
返回FALSE;
}
}
请注意我已经接受了字符串
在这里,因为这是我最常用的的TryParse
;否则, Convert.ChangeType
可能更合适。
我看不出有任何理由这是一个扩展方法(按这个
在问题的例子),而确实的,不宜污染对象
有太多的扩展方法。
Code taken from here
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.
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;
}
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;
}
}
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屋!