C# Bool 操作数用法
C# Bool operand usage
我想要得到以下结果
A B =
T T T
F T F
T F F
F F F
我正在使用这个条款来实现它
A || B
但它没有提供正确的结果。
我是否使用了错误的操作数?
您想要 and
,但您使用了 or
。
使用&&
(即'and')
||
表示 'or'
Am I using a wrong operand?
是的,你是。
您需要 AND &&
运算符,只有当所有条件都为 true.
您正在使用 OR ||
运算符,即使其中一个条件为 true,它也会为您提供 true。
使用 AND &&
运算符代替 OR ||
尽管所有其他答案都是正确的,但我想指出您要求的运算符既不是 ||
也不是 &&
。实际完全符合您要求的运算符是 &
(您错误使用的等效运算符是 |
)。
而且,有什么区别? ||
和 &&
是短路运算符。那是什么意思?这意味着运算符右侧的任何内容 仅在左侧为 true
时才计算 。这不会发生在运算符的非短路版本中(真正的布尔逻辑 and 和 or 运算符):
public bool True()
{
Console.WriteLine("True called.");
return true;
}
public bool False()
{
Console.WriteLine("False called.");
return false;
}
var b1 = False() && True(); //b1 will be false and "False called." will be
//printed on the console.
var b2 = False() & True(); //b2 will be false and "False called. True called."
//will be printed on the console.
我想要得到以下结果
A B =
T T T
F T F
T F F
F F F
我正在使用这个条款来实现它
A || B
但它没有提供正确的结果。
我是否使用了错误的操作数?
您想要 and
,但您使用了 or
。
使用&&
(即'and')
||
表示 'or'
Am I using a wrong operand?
是的,你是。
您需要 AND &&
运算符,只有当所有条件都为 true.
您正在使用 OR ||
运算符,即使其中一个条件为 true,它也会为您提供 true。
使用 AND &&
运算符代替 OR ||
尽管所有其他答案都是正确的,但我想指出您要求的运算符既不是 ||
也不是 &&
。实际完全符合您要求的运算符是 &
(您错误使用的等效运算符是 |
)。
而且,有什么区别? ||
和 &&
是短路运算符。那是什么意思?这意味着运算符右侧的任何内容 仅在左侧为 true
时才计算 。这不会发生在运算符的非短路版本中(真正的布尔逻辑 and 和 or 运算符):
public bool True()
{
Console.WriteLine("True called.");
return true;
}
public bool False()
{
Console.WriteLine("False called.");
return false;
}
var b1 = False() && True(); //b1 will be false and "False called." will be
//printed on the console.
var b2 = False() & True(); //b2 will be false and "False called. True called."
//will be printed on the console.