与 if 条件运算符相关的查询
我有一个方法,我做了类似的事情:
int? products= formvalues["number"] == "" ? (int?)null : Convert.ToInt32(formvalues["number"]);
if(products.HasValue)
{
// do some calulation
}
问题是如果产品有 0 或空值,我不想进行计算,否则进行计算,我该如何做到这一点,因为当前逻辑在其为空时避免计算,但它不避免产品价值为 0 时
I have got a method in which I have done something like:
int? products= formvalues["number"] == "" ? (int?)null : Convert.ToInt32(formvalues["number"]);
if(products.HasValue)
{
// do some calulation
}
The Issue is I dont want to do calculation if product has 0 or null value else do calculation, How can I do that as the current logic avoid calculation when its null but it doesnt avoid when the product has 0 value
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
这是有效的,因为
if
正在使用 短路评估:仅当product.HasValue
为 true 时才会评估products!=0
条件。编辑:
这个特定的 if 语句也可以在没有短路评估的情况下工作,因为
null!=0
- 如果您必须访问变量的成员,短路评估很有用通过在 if 语句中添加 null 检查作为前缀。另外,正如所指出的,
Nullable
提供了GetValueOrDefault()
方法来执行与上面相同的检查(@Bradley 得到了我的+1) - 在这种情况下,它是一个使用哪个取决于个人喜好/可读性。此外,您的问题的真正答案应该是使用
Int32.TryParse()
,而不是“手动”尝试验证输入。This works because
if
is using Short-circuit evaluation: theproducts!=0
condition is only evaluated ifproduct.HasValue
is true.Edit:
This particular if statement also would work without short-circuit evaluation since
null!=0
- short-circuit evluation is useful if you have to access a member of a variable by prefixing it with a null check in the if statement.Also as pointed out
Nullable<T>
provides theGetValueOrDefault()
method to do the same check as above (@Bradley got my +1) - in this case it is a matter of personal preference /readability which to use.Also the real answer your question should be to use
Int32.TryParse()
instead of "manually" trying to validate the input.使用原始代码,您可以编写:
GetValueOrDefault
products为null
,a>将返回0。但是,我可能会按如下方式编写(以避免
Convert.ToInt32
无法解析用户提交的数据时引发潜在的FormatException
):Using your original code, you could write:
GetValueOrDefault
will return 0 ifproducts
isnull
.However, I would probably write it as follow (to avoid a potential
FormatException
thrown byConvert.ToInt32
failing to parse user-submitted data):摆脱可为空的 int 并执行更安全的转换:
Get rid of the nullable int and perform a safer conversion:
试试这个
Try this
我更喜欢这个
if((products ?? 0) != 0){}
I prefer this
if((products ?? 0) != 0){}