Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/307.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/variables/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 值为0时的强制转换错误浮点到双精度_C#_Variables_Dataset_Sqldatatypes - Fatal编程技术网

C# 值为0时的强制转换错误浮点到双精度

C# 值为0时的强制转换错误浮点到双精度,c#,variables,dataset,sqldatatypes,C#,Variables,Dataset,Sqldatatypes,当数据库中的price值为0.0时,下面的C#代码位就会给我一个转换错误。字段类型是从中读取它的数据库中的一个浮点。有人知道这个问题吗 double decPrice = (double)dsqry2.Tables[0].Rows[intCountOrders]["Price"]; 使用而不是铸造 double decPrice = Convert.ToDouble(dsqry2.Tables[0].Rows[intCountOrders]["Price"]); 我最喜欢和最安全的解决方案很

当数据库中的price值为0.0时,下面的C#代码位就会给我一个转换错误。字段类型是从中读取它的数据库中的一个浮点。有人知道这个问题吗

double decPrice = (double)dsqry2.Tables[0].Rows[intCountOrders]["Price"];
使用而不是铸造

double decPrice = Convert.ToDouble(dsqry2.Tables[0].Rows[intCountOrders]["Price"]);

我最喜欢和最安全的解决方案很简单:

var x = dsqry2.Tables[0].Rows[intCountOrders]["Price"];
var decPrice = x is double ? (double)x : 0;
试一试

dsqry2.Tables[0]。行[intCountOrders]。字段(“价格”)

您确定这是实际错误吗?在我看来,
表[0]。行[intCountOrders][“Price”]
可能是可空的且为空。如果值为null,您看到的0.0(where?)可能就是您看到的值。因此,您可能需要在阉割之前检查空值。您确定它是
0.0
而不是
DBNull.Value
?可以尝试
Double.parseDouble(dsqry2.Tables[0].Rows[intCountOrders][“Price”]装箱值类型不能转换为该类型的同一类型或
可为null
以外的其他类型。你所做的不是演员阵容。这是拆箱,你想解释一下吗?无论值是double还是DBNull,它都能完美地工作。@SriramSakthivel显示一个失败的测试用例。我现在使用的是
DateTime?
列,如果值不是
DBNull
,则
是DateTime
返回true,此时强制转换也起作用;var x=obj;var decPrice=x是双倍的吗?(双)x:0;尝试此
decPrice
将0@SriramSakthivel当然会,因为
float
不是
double
。实际情况是,对象可以包含
double
DBNull
。如果数据类型不兼容,则问题不同。如果数据类型是float,只需在我的回答中将每个
double
替换为
float
,就可以了。这同样适用于
bool
DateTime
等等。无论哪种方式,您都需要在不同层之间匹配数据类型。这是逻辑。请阅读问题OP清楚地提到它是浮动的。字段类型是数据库中的浮点型。那么这个解决方案是怎么起作用的呢?
dsqry2.Tables[0].Rows[intCountOrders].Field<double>("Price")