我正在尝试创建一个通用扩展,使用'TryParse'来检查字符串是否是给定类型:
public static bool Is<T>(this string input)
{
T notUsed;
return T.TryParse(input, out notUsed);
}
Run Code Online (Sandbox Code Playgroud)
这将无法编译,因为它无法解析符号'TryParse'
据我了解,'TryParse'不是任何界面的一部分.
这有可能吗?
更新:
使用下面的答案,我想出了:
public static bool Is<T>(this string input)
{
try
{
TypeDescriptor.GetConverter(typeof(T)).ConvertFromString(input);
}
catch
{
return false;
}
return true;
}
Run Code Online (Sandbox Code Playgroud)
它运作得很好,但我认为以这种方式使用异常对我来说感觉不对.
UPDATE2:
修改为传递类型而不是使用泛型:
public static bool Is(this string input, Type targetType)
{
try
{
TypeDescriptor.GetConverter(targetType).ConvertFromString(input);
return true;
}
catch
{
return false;
}
}
Run Code Online (Sandbox Code Playgroud) 我正在尝试进行一些数据转换.不幸的是,大部分数据都是字符串,它应该是int或double等等......
所以我得到的是:
double? amount = Convert.ToDouble(strAmount);
Run Code Online (Sandbox Code Playgroud)
这种方法的问题是如果strAmount是空的,如果它是空的我希望它等于null,所以当我将它添加到数据库时,该列将为null.所以我最后写了这个:
double? amount = null;
if(strAmount.Trim().Length>0)
{
amount = Convert.ToDouble(strAmount);
}
Run Code Online (Sandbox Code Playgroud)
现在这个工作正常,但我现在有五行代码而不是一行代码.这使得事情变得更难以阅读,特别是当我有大量的列要转换时.
我以为我会使用字符串类和泛型的扩展来传入类型,这是因为它可能是double,或int或long.所以我尝试了这个:
public static class GenericExtension
{
public static Nullable<T> ConvertToNullable<T>(this string s, T type) where T: struct
{
if (s.Trim().Length > 0)
{
return (Nullable<T>)s;
}
return null;
}
}
Run Code Online (Sandbox Code Playgroud)
但我收到错误:无法将类型'string'转换为'T?'
有没有解决的办法?我不太熟悉使用泛型创建方法.