Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/algorithm/10.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# “懒惰”;及;表达式求值_C#_Lazy Evaluation_Boolean Expression - Fatal编程技术网

C# “懒惰”;及;表达式求值

C# “懒惰”;及;表达式求值,c#,lazy-evaluation,boolean-expression,C#,Lazy Evaluation,Boolean Expression,我一直在使用下面的代码块请求用户输入,并在控制台应用程序中检查其有效性 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

我一直在使用下面的代码块请求用户输入,并在控制台应用程序中检查其有效性

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
do
{
Console.Write(“输入X值:”;//提示符
}而(!(int.TryParse(Console.ReadLine(),out temp)和&(temp=0));//如果无法将输入解析为整数或超出范围,请重复此操作
“&&”(and)表达式是惰性的,这是一个有文档记录的特性吗?ie:如果第一个操作数为false,那么它不会解析第二个操作数?我可以在生产构建中依赖它吗?我能期望它在其他编译器中的行为相同吗?
这是我在PPCG.SE中学到的东西

此外,能否使块更易于阅读或简化为一行程序

“&&”(and)表达式计算的是文档化的功能吗 他懒惰吗

条件AND运算符(&&)对其bool操作数执行逻辑AND,但仅在必要时计算其第二个操作数。换句话说,它是一个短路操作符

我可以在生产构建中依赖它吗?我能预料到吗 在其他编译器中的行为是否相同

是的,它的行为应该总是一样的

此外,可以使块更易于读取或简化为 单程票

除了删除一些冗余参数外,不能仅使用一行来简化此操作

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

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

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

,这里是C语言规范中有关
&
|
的相关部分:

第7.12节条件逻辑运算符

&&和| |运算符是&和的条件版本| 操作员:

  • 操作x和y对应于操作x和y, 除非只有当x不为false时才计算y
  • 运算x | | y与运算x | y相对应,只是只计算y 如果x不是真的

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

作为补充说明,
&&
|
通常被称为“短路操作员”,因为这种行为。大多数主要编程语言都是这样对待它们的。如果你愿意的话,你会发现令人惊讶的是:“条件AND运算符(&&&)对它的布尔操作数执行逻辑AND运算,但只有在必要时才计算它的第二个操作数。”
while (!(int.TryParse(Console.ReadLine(), out temp) && IsValidRange(temp)));