Use*_*ser 7 c# c++ deterministic non-deterministic
情况:使用许多条件在C++或C#中进行条件检查:
if (condition1 && condition2 && condition3)
{
// Do something
}
Run Code Online (Sandbox Code Playgroud)
我一直认为不能保证执行这些检查的顺序.所以它不一定是条件1然后是条件2,而不是条件3.我在C++的时代学到了它.我想我被告知或在某处阅读.
直到知道我总是编写安全代码来解决在以下情况下可能的空指针:
if ((object != null) && (object.SomeFunc() != value))
{
// A bad way of checking (or so I thought)
}
Run Code Online (Sandbox Code Playgroud)
所以我在写:
if (object != null)
{
if (object.SomeFunc() != value)
{
// A much better and safer way
}
}
Run Code Online (Sandbox Code Playgroud)
因为我不确定首先运行非空检查,然后才会调用实例方法来执行第二次检查.
现在,我们最伟大的社区头脑告诉我,执行这些检查的顺序保证以从左到右的顺序运行.
我很惊讶.对C++和C#语言来说真的如此吗?
有没有人听过我之前听过的版本?
Rob*_*son 14
简短回答是从左到右进行短路评估.订单是可预测的.
// perfectly legal and quite a standard way to express in C++/C#
if( x != null && x.Count > 0 ) ...
Run Code Online (Sandbox Code Playgroud)
有些语言在分支之前评估条件中的所有内容(例如VB6).
// will fail in VB6 if x is Nothing.
If x Is Not Nothing And x.Count > 0 Then ...
Run Code Online (Sandbox Code Playgroud)
参考:MSDN C#运营商及其顺序或优先顺序.
| 归档时间: |
|
| 查看次数: |
4121 次 |
| 最近记录: |