我正在尝试进行一些数据转换。不幸的是,大部分数据都在字符串中,应该是整型或双精度型,等等。
所以我得到的是这样的:
double? amount = Convert.ToDouble(strAmount);
这种方法的问题是,如果strAmount为空,如果它为空,我希望它为null,所以当我将其添加到数据库中时,列将为null。所以我最终写了这篇文章:
double? amount = null;
if(strAmount.Trim().Length>0)
{
amount = Convert.ToDouble(strAmount);
}
现在可以很好地工作了,但是我现在有5行代码,而不是1行。这使得阅读起来有点困难,特别是当我有大量的列要转换的时候。
我想我应该使用string类和泛型的扩展来传入类型,这是因为它可以是双精度型、整型或长整型。所以我试了一下:
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?’
有什么办法可以解决这个问题吗?我对使用泛型创建方法不是很熟悉。
发布于 2009-04-21 15:19:16
另一件要记住的事情是字符串本身可能是空的。
public static Nullable<T> ToNullable<T>(this string s) where T: struct
{
Nullable<T> result = new Nullable<T>();
try
{
if (!string.IsNullOrEmpty(s) && s.Trim().Length > 0)
{
TypeConverter conv = TypeDescriptor.GetConverter(typeof(T));
result = (T)conv.ConvertFrom(s);
}
}
catch { }
return result;
}
发布于 2009-04-21 15:19:25
您可以尝试使用以下扩展方法:
public static T? GetValueOrNull<T>(this string valueAsString)
where T : struct
{
if (string.IsNullOrEmpty(valueAsString))
return null;
return (T) Convert.ChangeType(valueAsString, typeof(T));
}
通过这种方式,您可以执行以下操作:
double? amount = strAmount.GetValueOrNull<double>();
int? amount = strAmount.GetValueOrNull<int>();
decimal? amount = strAmount.GetValueOrNull<decimal>();
发布于 2009-04-21 15:16:09
这样如何:
double? amount = string.IsNullOrEmpty(strAmount) ? (double?)null : Convert.ToDouble(strAmount);
当然,这没有考虑到转换失败。
https://stackoverflow.com/questions/773078
复制相似问题