这个 if 语句会导致不好的事情发生吗?

发布于 2024-09-06 11:24:55 字数 345 浏览 2 评论 0原文

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

不爱素颜 2024-09-13 11:24:55

没关系。 && 在 C# 中是短路的,out 参数在 之前肯定已经被 TryParse 分配了合适的值调用 ContainsKey

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

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";
}

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

That's fine. && is short-circuiting in C#, and the out parameter will definitely have been assigned the appropriate value by TryParse before ContainsKey is called.

On the other hand, you could use the same trick again to fetch the value:

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";
}

This way you're only doing the lookup of the expense code once.

风铃鹿 2024-09-13 11:24:55

不,不会导致不好的事情发生!

&& 运算符保证如果左操作数的计算结果为 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.

濫情▎り 2024-09-13 11:24:55

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

The statement is fine, && will short circuit, which means the right hand side is contingent upon the left. So if TryParse returns true, then expenseCode will be populated with a valid integer, and then the right function will execute.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文