Convert string to nullable type (int, double, etc...)(将字符串转换为可空类型(int、double 等...))
问题描述
我正在尝试进行一些数据转换.不幸的是,大部分数据都在字符串中,应该是 int 或 double 等......
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 为空,如果它是空的,我希望它为空,所以当我将它添加到数据库中时,该列将为空.所以我最终写了这个:
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);
}
现在这工作正常,但我现在有五行代码而不是一行.这使事情变得更难阅读,尤其是当我有大量列要转换时.
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.
我想我会使用对字符串类和泛型的扩展来传递类型,这是因为它可以是双精度、整数或长整数.所以我尝试了这个:
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、double 等...)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:将字符串转换为可空类型(int、double 等...)
基础教程推荐
- 全局 ASAX - 获取服务器名称 2022-01-01
- 如何动态获取文本框中datagridview列的总和 2022-01-01
- 错误“此流不支持搜索操作"在 C# 中 2022-01-01
- 经典 Asp 中的 ResolveUrl/Url.Content 等效项 2022-01-01
- 在 VS2010 中的 Post Build 事件中将 bin 文件复制到物 2022-01-01
- 是否可以在 asp classic 和 asp.net 之间共享会话状态 2022-01-01
- 从 VS 2017 .NET Core 项目的发布目录中排除文件 2022-01-01
- 将事件 TextChanged 分配给表单中的所有文本框 2022-01-01
- 首先创建代码,多对多,关联表中的附加字段 2022-01-01
- JSON.NET 中基于属性的类型解析 2022-01-01
