通用 TryParse [英] Generic TryParse
本文介绍了通用 TryParse的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试创建一个使用TryParse"来检查字符串是否为给定类型的通用扩展:
I am trying to create a generic extension that uses 'TryParse' to check if a string is a given type:
public static bool Is<T>(this string input)
{
T notUsed;
return T.TryParse(input, out notUsed);
}
这不会编译,因为它无法解析符号TryParse"
this won't compile as it cannot resolve symbol 'TryParse'
据我所知,TryParse"不是任何界面的一部分.
As I understand, 'TryParse' is not part of any interface.
这有可能吗?
更新:
使用以下我得出的答案:
Using the answers below I have come up with:
public static bool Is<T>(this string input)
{
try
{
TypeDescriptor.GetConverter(typeof(T)).ConvertFromString(input);
}
catch
{
return false;
}
return true;
}
它工作得很好,但我认为以这种方式使用异常对我来说并不合适.
It works quite well but I think using exceptions in that way doesn't feel right to me.
更新 2:
修改为传递类型而不是使用泛型:
Modified to pass type rather than use generics:
public static bool Is(this string input, Type targetType)
{
try
{
TypeDescriptor.GetConverter(targetType).ConvertFromString(input);
return true;
}
catch
{
return false;
}
}
推荐答案
您应该使用 TypeDescriptor 类:
public static T Convert<T>(this string input)
{
try
{
var converter = TypeDescriptor.GetConverter(typeof(T));
if(converter != null)
{
// Cast ConvertFromString(string text) : object to (T)
return (T)converter.ConvertFromString(input);
}
return default(T);
}
catch (NotSupportedException)
{
return default(T);
}
}
这篇关于通用 TryParse的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文