我正在尝试创建一个使用“TryParse”来检查字符串是否为给定类型的通用扩展:
public static bool Is<T>(this string input)
{
T notUsed;
return T.TryParse(input, out notUsed);
}
这不会编译,因为它无法解析符号 'TryParse'
据我所知,'TryParse' 不是任何接口(interface)的一部分。
这有可能吗?
更新:
使用以下我得出的答案:
public static bool Is<T>(this string input)
{
try
{
TypeDescriptor.GetConverter(typeof(T)).ConvertFromString(input);
}
catch
{
return false;
}
return true;
}
它工作得很好,但我认为以这种方式使用异常对我来说并不合适。
更新2:
修改为传递类型而不是使用泛型:
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);
}
}
关于c# - 通用 TryParse,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2961656/