惰性 "and" 表达式求值

Lazy "and" expression evaluation

我一直在使用以下代码块来询问用户输入并在控制台应用程序中检查其有效性。

do
{
    Console.Write("Enter X value:");    // prompt
} while (!(int.TryParse(Console.ReadLine(),out temp) && (temp<=10) && (temp>=0))); // repeat if input couldn't be parsed as an integer or out of range

“&&”(和)表达式求值是惰性的,这是一个文档化的特征吗?即:如果第一个操作数为假,那么它不会解析第二个操作数?我可以在生产构建中依赖它吗?我可以期望它在其他编译器中的行为相同吗?
这是我在 PPCG.SE

中捡到的东西

此外,是否可以使块更易于阅读或简化为单行?

Is it a documented feature that the "&&" (and) expression evaluating is lazy?

Yes as mentioned on the C# reference page:

条件与运算符 (&&) 执行其布尔操作数的逻辑与,但仅在必要时评估其第二个操作数。换句话说,它是一个短路运算符

Can I rely on it in production builds? Can I expect that it would behave the same in other compilers?

是的,它应该始终表现相同。

Additionally, can the block be made simpler to read or simplified into a oneliner?

除了去掉一些多余的参数外,你不能只用一行来简化它。

但是,您可以通过将 (temp<=10) && (temp>=0) 的逻辑隐藏到某些方法中来使其更具可读性,例如:

public static bool IsValidRange(int temp) =>  temp >= 0 && temp <= 10;

然后你的 while 条件变为:

while (!(int.TryParse(Console.ReadLine(), out temp) && IsValidRange(temp)));

现在方法的名称读作问题陈述 IsValidRange

这是 C# 语言规范中讨论 &&|| 的相关部分:

Section 7.12 Conditional Logical Operators

The && and || operators are conditional versions of the & and | operators:

  • The operation x && y corresponds to the operation x & y, except that y is evaluated only if x is not false.
  • The operation x || y corresponds to the operation x | y, except that y is evaluated only if x is not true.

因为它在规范中,所以无论您使用什么编译器,它的行为都应该相同。如果不是,则您使用的编译器不被视为 "C#" 编译器。 :)