c# - 转换不断出现错误

标签 c# casting double

我有一个包含以下数据的 CSV(无标题)

12,2010,76.5
2,2000,45
12,1940,30.2

我正在将数据读入 List<List<object>> .

要了解每行和每列/行中的内容,我使用以下循环

List<List<object>> data = CSVReaderNoHeader.Read("input")

for (var i = 0; i < data.Count; i++)
{

    double month = (double)(int)data[i][0];
    print($"month:{month} ////END");

    double year= (double)(int)data[i][1];
    print($"year:{year} ////END");

    double temperature= (double)data[i][2];
    print($"temperature:{temperature} ////END");

}

是的,我需要创建 double ,这就是我拆箱和转换的原因(可以使用 double.Parse 代替)。

我可以很好地打印月份和年份,但是当达到 double temperature= (double)data[i][2]; 时,抛出以下错误

InvalidCastException: Specified cast is not valid.

我在该行 ( print(data[i][2]); ) 之前打印了 data[i][2] 中的内容,只是为了看看那里的一切是否都按顺序排列,并按预期得到了 76.5 。然后,还使用进行了测试

double temperature= (double)(double)data[i][2];
double temperature= (double)(float)data[i][2];

(我认为没有必要添加额外的(双)/(浮点))和

object tempr = data[i][2];
double temperature;
temperature = (double)tempr;

但问题仍然存在。于是,我继续跑print(data[i][2].GetType());查看返回的类型是否可以转换为 double 型。我得到的结果是System.String

知道了这一点,然后我尝试了方法 double.TryParse、double.Parse 和 Convert.ToDouble 但没有奏效

double.TryParse(data[i][2], out temperature);

Argument 1: cannot convert from 'object' to string.

double temperature = double.TryParse(data[i][2]);

Argument 1: cannot convert from 'object' to string.

double temperature = System.Convert.ToDouble(data[i][2]);

FormatException: Input string was not in a correct format.

那我该如何转换它呢?

最佳答案

因为您的数字使用点作为小数点分隔符,并且您的系统本地化可以使用不同的点,所以您可以使用它:

using System.Xml;

double temperature = XmlConvert.ToDouble(data[i][2].ToString());

如果解析错误,它将引发异常。

所以你可以尝试...catch来管理它。

也许您需要将 System.Xml 添加到项目的程序集引用中。

否则你可以使用@Fabjan解决方案:

if (double.TryParse(data[i][2].ToString(),
                    System.Globalization.NumberStyles.Any,
                    System.Globalization.CultureInfo.InvariantCulture,
                    out var temperature);
  IsOk();
else
  IsNotOk();

关于c# - 转换不断出现错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58772172/

相关文章:

c# - 与 String 连接或转换为 String 时出现 Double 类型的奇怪行为

c# - 如何在 C# 中计算非常大的 double 组的轮数

c - 需要帮忙进行数组赋值

C# 使用 LiveCharts 将图表转为图像

时间:: when can I know that webbrowser controller Url changed to a specific url?

java - 从字符串到泛型的转换

java - 消除未经检查的警告: cast String to T

c# - 是否有用于解析字符串以创建 C# 函数的工具?

c# - 带下划线的 Newton CamelCase 问题

c++ - 如何通过转换类型指针将 char 数组转换为 uint16_t?