可空对象必须具有基于方程的值

问题描述 投票:0回答:1

我有一个 SQL 数据库,我要从中提取数据。但是,其中一些数据未测量,因此为 NULL。我已经能够使用此方法避免一些空值:

if (dataItem.Feature1!= null) { 
 trainingCategorial.Feature1= (float)dataItem.Feature1; 
}
else { 
 trainingCategorial.Feature1= float.NaN; 
}

dataItem 是我用 foreach 迭代的数据集。

foreach (dataItem in dataset)

但是,现在我有同样的问题,但有一个方程:

if(dataItem.CalculateFeature2(afdKenm, (decimal)dataItem.Feature3) != null)
{
 trainingCategorial.Feature2 = 
 dataItem.CalculateFeature2(afdKenm, (decimal)dataItem.Feature3)  > 0;
}

代码的目标是创建一个Feature2 的布尔值。我检查过,feature3 似乎没有任何 NULL 值。我的问题在于我的 c# 代码在给出错误之前甚至不想检查 dataItem.CalculateFeatures2 。 它只是立即说“可为 Null 的对象必须有一个值”。

有人可以帮我吗?预先感谢您!

c# nullable
1个回答
0
投票

我尝试检查是否存在空值:

int count = 0;
if (Feature3 = null){
count++;}

但是,这不起作用,我的数据库中确实存在空值。我很困惑,因为我之前已经使用过类似的方法,但该数据集中没有任何空值。 最后我自己计算了Feature3,现在代码确实可以运行了。

感谢您的帮助!对于其他在这个问题上苦苦挣扎的人: 如果您使用的是

if(dataItem != Null)

在 if 函数中使用断点,因为如果它在调试中没有进入那里,那么您也知道数据集中存在 NULL 值,您可以适当地处理它们。

© www.soinside.com 2019 - 2024. All rights reserved.