|| 运算符执行逻辑或。
它将首先评估左操作数,如果为真,则表达式为真。如果左操作数为假,则计算第二个操作数。
如果您将以下示例作为控制台应用程序运行,您将看到会发生什么:
using System;
namespace OrOperand
{
class Program
{
static void Main(string[] args)
{
DisplayResult(true, true);
DisplayResult(true, false);
DisplayResult(false, true);
DisplayResult(false, false);
}
private static void DisplayResult(bool left, bool right)
{
_left = left;
_right = right;
Console.WriteLine("Running " + left + " || " + right);
if (Left() || Right())
{
Console.WriteLine(_left + " || " + _right + " is true");
}
else
{
Console.WriteLine(_left + " || " + _right + " is false");
}
}
static bool _left = true;
static bool _right = false;
static bool Left()
{
Console.WriteLine("Left called");
return _left;
}
static bool Right()
{
Console.WriteLine("Right called");
return _right;
}
}
}
这将输出:
Running True || True
Left called
True || True is true
Running True || False
Left called
True || False is true
Running False || True
Left called
Right called
False || True is true
Running False || False
Left called
Right called
False || False is false