C# 无法将类型 'System.Double' 的对象转换为类型 'System.Single'

C# Unable to cast object of type 'System.Double' to type 'System.Single'

在判断此问题已经回答之前,请阅读说明。我在下面有这个简单的代码:

Dictionary<string, object> d = new Dictionary<string, object>();

d.Add("key" , 30d);

System.Diagnostics.Debug.WriteLine($" TYPE OF OBJECT IS  \"{d["key"].GetType()}\"");

netPlannedHours = (float)d["key"];         ---> **Line of Interest**

当我执行这个时,我得到:

TYPE OF OBJECT IS "System.Double" Exception thrown: 'System.InvalidCastException' in DevOpsAutomatedReporting.dll Unable to cast object of type 'System.Double' to type 'System.Single'.

异常是由标记为“兴趣线”的最后一行引起的。我真的不明白为什么最后一行会导致此问题,因为对象的类型在运行时被推断为“System.Double”,因此它应该将其转换为浮点数,但事实并非如此。有趣的一点是,如果我用以下两行代码中的任何一行替换最后一行(“感兴趣的行”),它会成功地将 double 转换为 float

// Cast the double object to double again and then to float **WORKS**
netPlannedHours = (float)(double)d["key"];
  
// Convert to float using "Convert.ToSingle()"  **WORKS**
netPlannedHours = Convert.ToSingle(d["key"]);

当你添加到字典中时,你的双精度将被装箱,因为字典将 string 映射到 object

拆箱时必须转换为基础类型。在您的情况下,基础类型是 double,因此转换为 float 将失败。

您可以使用 Convert.ToSingle

来解决这个问题
netPlannedHours = Convert.ToSingle(d["key"])

此方法将计算出基础类型并可以进行转换,但在计算类型转换时会降低性能。

我今天遇到了类似的问题,我的 SQL 实体映射为“float”,我的 .Net 实体映射为“float”。我保留了 SQL 映射,但将 .Net 类型更改为“double”。

ADO.NET SQL Server Data Type Mappings 文档提供了 table 所有类型的正确映射。