我正在try 进行一些数据转换.不幸的是,很多数据都在字符串中,其中应该是整型或双精度型,依此类推……
所以我得到的是:
double? amount = Convert.ToDouble(strAmount);
这种方法的问题是,如果strAmount为空,如果它为空,我希望它的值为null,因此当我将其添加到数据库中时,列将为null.所以我最后写了这样一篇:
double? amount = null;
if(strAmount.Trim().Length>0)
{
amount = Convert.ToDouble(strAmount);
}
现在这很好,但我现在有五行代码,而不是一行.这使得阅读起来有点困难,尤其是当我有大量的列要转换时.
我想我应该使用string类和泛型的扩展来传递类型,这是因为它可以是double、int或long.所以我try 了这个:
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;
}
}
但我得到了一个错误:无法将类型"string"转换为"T"
有办法吗?我不太熟悉使用泛型创建方法.