将字符串转换为可空类型(INT,双,等...) [英] Convert string to nullable type (int, double, etc...)
问题描述
我在尝试做一些数据转换。不幸的是,许多数据是字符串,它应该是int的或双,等...
I am attempting to do some data conversion. Unfortunately, much of the data is in strings, where it should be int's or double, etc...
所以,我所得到的是这样的:
So what I've got is something like:
double? amount = Convert.ToDouble(strAmount);
使用这种方法的问题是,如果strAmount是空的,如果它是空的我希望它相当于为null,所以当我将其添加到数据库中的列将为空。所以,我最后写的:
The problem with this approach is if strAmount is empty, if it's empty I want it to amount to be null, so when I add it into the database the column will be null. So I ended up writing this:
double? amount = null;
if(strAmount.Trim().Length>0)
{
amount = Convert.ToDouble(strAmount);
}
现在这工作得很好,但我现在有五行code而不是一个。这使事情变得更难看了,尤其是当我有大量的列进行转换。
Now this works fine, but I now have five lines of code instead of one. This makes things a little more difficult to read, especially when I have a large amount of columns to convert.
我想我会用一个扩展字符串类和通用的传入的类型,这是因为它可能是一个双,或int或长。所以,我想这样的:
I thought I'd use an extension to the string class and generic's to pass in the type, this is because it could be a double, or an int, or a long. So I tried this:
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;
}
}
但我得到的错误:'T'无法将类型字符串来
But I get the error: Cannot convert type 'string' to 'T?'
有没有解决的办法吗?我不是很熟悉创建使用泛型方法。
Is there a way around this? I am not very familiar with creating methods using generics.
推荐答案
另一件事要记住的是字符串本身可能为空。
Another thing to keep in mind is that the string itself might be null.
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;
}
这篇关于将字符串转换为可空类型(INT,双,等...)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!