这个 if 语句会导致不好的事情发生吗?
int expenseCode;
if (int.TryParse(sourceRecord.ExpenseCode, out expenseCode) && _ExpenseCodeLookup.ContainsKey(expenseCode))
{
destRow.PROFIT_CENTER_NAME = _ExpenseCodeLookup[expenseCode];
}
else
destRow.PROFIT_CENTER_NAME = "Unknown";
我担心的是第一个表达式是否总是在第二个操作之前运行(在进程中设置expenseCode
)?
int expenseCode;
if (int.TryParse(sourceRecord.ExpenseCode, out expenseCode) && _ExpenseCodeLookup.ContainsKey(expenseCode))
{
destRow.PROFIT_CENTER_NAME = _ExpenseCodeLookup[expenseCode];
}
else
destRow.PROFIT_CENTER_NAME = "Unknown";
The thing I am conerned about is will the first expression always be run (setting expenseCode
in the process) before the second operation?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
没关系。
&&
在 C# 中是短路的,out
参数在之前肯定已经被
。TryParse
分配了合适的值调用 ContainsKey另一方面,您可以再次使用相同的技巧来获取值:
这样您只需查找费用代码一次。
That's fine.
&&
is short-circuiting in C#, and theout
parameter will definitely have been assigned the appropriate value byTryParse
beforeContainsKey
is called.On the other hand, you could use the same trick again to fetch the value:
This way you're only doing the lookup of the expense code once.
不,不会导致不好的事情发生!
&&
运算符保证如果左操作数的计算结果为 false,则不会计算右操作数。这称为短路。同样,如果左操作数的计算结果为 true,则
||
运算符将不会计算右操作数。这些布尔值运算符的非短路版本是
&
和|
。无论左侧的值如何,它们都会计算两个操作数。No, it won't cause bad things to happen!
The
&&
operator guarantees not to evaluate the right operand if the left operand evaluates to false. This is called short-circuiting.Similarly,
||
operator will not evaluate the right operand if the left operand evaluates to true.The non-short-circuiting versions of these operators for boolean values are
&
and|
. They will evaluate both operands regardless of the value of the left hand side.语句很好,
&&
会短路,这意味着右侧取决于左侧。因此,如果TryParse
返回 true,则expenseCode
将填充有效整数,然后执行正确的函数。The statement is fine,
&&
will short circuit, which means the right hand side is contingent upon the left. So ifTryParse
returns true, thenexpenseCode
will be populated with a valid integer, and then the right function will execute.