gpt4 book ai didi

c# - 将字符串转换为可空类型(int、double 等...)

转载 作者:IT王子 更新时间:2023-10-29 03:33:03 26 4
gpt4 key购买 nike

我正在尝试进行一些数据转换。不幸的是,大部分数据都是字符串,它应该是 int 或 double 等......

所以我得到的是这样的:

double? amount = Convert.ToDouble(strAmount);

这种方法的问题是,如果 strAmount 为空,如果它为空,我希望它的 amount 为空,所以当我将它添加到数据库中时,该列将为空。所以我最后写了这个:

double? amount = null;
if(strAmount.Trim().Length>0)
{
amount = Convert.ToDouble(strAmount);
}

现在一切正常,但我现在有五行代码而不是一行。这让事情变得有点难以阅读,尤其是当我有大量的列要转换时。

我想我会使用字符串类和泛型的扩展来传递类型,这是因为它可能是 double 型、整数型或长型。所以我尝试了这个:

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?”

有解决办法吗?我不太熟悉使用泛型创建方法。

最佳答案

要记住的另一件事是字符串本身可能为空。

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;
}

关于c# - 将字符串转换为可空类型(int、double 等...),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/773078/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com