我正在尝试进行一些数据转换.不幸的是,大部分数据都是字符串,它应该是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?'
有没有解决的办法?我不太熟悉使用泛型创建方法.
假设我有一个方法,将int作为字符串,如果解析成功则返回int,否则返回null值.
int? ParseValue(string intAsString)
{
int i;
if (int.TryParse(intAsString, out i))
return i;
return null;
}
Run Code Online (Sandbox Code Playgroud)
如何重写这个方法,使它不仅可以用于int?,还可以用long ?, decimal?和日期时间??