6
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?

4

3 回答 3

15

没关系。&&在 C# 中是短路的,并且在调用之前out肯定会为参数分配适当的值。TryParseContainsKey

另一方面,您可以再次使用相同的技巧来获取值:

string profitCenter;
int expenseCode;
if (int.TryParse(sourceRecord.ExpenseCode, out expenseCode) && 
    _ExpenseCodeLookup.TryGetValue(expenseCode, out profitCenter))
{
    destRow.PROFIT_CENTER_NAME = profitCenter;
}
else
{
    destRow.PROFIT_CENTER_NAME = "Unknown";
}

这样,您只需查找一次费用代码。

于 2010-06-23T20:19:31.513 回答
6

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.

于 2010-06-23T20:19:24.517 回答
3

语句很好,&&会短路,这意味着右手边是左手边。因此,如果TryParse返回 true,expenseCode则将填充一个有效的整数,然后执行正确的函数。

于 2010-06-23T20:20:13.943 回答