铸造不断出错

Casting keeps on getting errors

我有一个包含以下数据的 CSV(没有 header)

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.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];

(我认为没有必要添加额外的 (double) / (float))和

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

但问题依旧。所以,我继续 运行 print(data[i][2].GetType()); 看看那里返回的类型是否可以转换为双精度型。结果我得到 System.String.

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

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();