查询与if条件运算符相关

Mr *_*r A 1 c# if-statement

我有一个方法,我做了类似的事情:

int? products= formvalues["number"] == "" ? (int?)null : Convert.ToInt32(formvalues["number"]);
if(products.HasValue)
{ 
    // do some calulation
}
Run Code Online (Sandbox Code Playgroud)

问题是我不想做计算,如果产品有0或空值,否则做计算,我怎么能这样做,因为当前逻辑避免计算时它的null但它不避免当产品有0值

Bro*_*ass 7

if(products.HasValue && products !=0)
{ 
    // do some calculation
}
Run Code Online (Sandbox Code Playgroud)

这是因为if使用短路评估:products!=0仅在条件product.HasValue为真时评估条件.

编辑:

这个特殊的if语句也可以在没有短路评估的情况下工作 - 因为null!=0如果你必须通过在if语句前面加上空值检查来访问变量的成员,那么短路验证很有用.

另外正如所指出的那样Nullable<T>提供了GetValueOrDefault()进行上述相同检查的方法(@Bradley获得了我的+1) - 在这种情况下,它是个人偏好/可读性的问题.

你问题的真正答案应该是使用Int32.TryParse()而不是"手动"尝试验证输入.


Bra*_*ger 5

使用原始代码,您可以写:

if (products.GetValueOrDefault() != 0)
{
    // do some calulation
}
Run Code Online (Sandbox Code Playgroud)

GetValueOrDefault如果products是,将返回0 null.

但是,我可能会按如下方式编写它(以避免因解析用户提交的数据而导致的潜在FormatException抛出Convert.ToInt32):

int products;
if (int.TryParse(formvalues["number"], out products) && products != 0)
{
    // do some calculation
}
Run Code Online (Sandbox Code Playgroud)