|| 運算子 (C# 參考)
OR 條件運算子 ()||執行邏輯 OR 其 bool 運算元。如果第一個運算元評估為 true,第二個運算元不會評估。如果第一個運算元評估為 false,第二個運算子判斷或整個運算式是否可以評估為 true 或 false。
備註
運算
x || y
對應到這項運算
x | y
但是,如果 x 是 true, y 不會評估 y,不論的值,因為或作業是 true 。這個概念稱為「最少運算評估」。
OR 條件運算子無法多載,不過,標準邏輯運算子 true 和 錯誤 和運算子的多載,有某些限制,也視為條件邏輯運算子的多載。
範例
在下列範例中,使用的 || 運算式只評估第一個運算元。使用的運算式|評估的兩個運算元。在第二個範例中,則為,如果兩個運算元都評估為,則會產生執行階段例外狀況時發生。
class ConditionalOr
{
// Method1 returns true.
static bool Method1()
{
Console.WriteLine("Method1 called.");
return true;
}
// Method2 returns false.
static bool Method2()
{
Console.WriteLine("Method2 called.");
return false;
}
static bool Divisible(int number, int divisor)
{
// If the OR expression uses ||, the division is not attempted
// when the divisor equals 0.
return !(divisor == 0 || number % divisor != 0);
// If the OR expression uses |, the division is attempted when
// the divisor equals 0, and causes a divide-by-zero exception.
// Replace the return statement with the following line to
// see the exception.
//return !(divisor == 0 | number % divisor != 0);
}
static void Main()
{
// Example #1 uses Method1 and Method2 to demonstrate
// short-circuit evaluation.
Console.WriteLine("Regular OR:");
// The | operator evaluates both operands, even though after
// Method1 returns true, you know that the OR expression is
// true.
Console.WriteLine("Result is {0}.\n", Method1() | Method2());
Console.WriteLine("Short-circuit OR:");
// Method2 is not called, because Method1 returns true.
Console.WriteLine("Result is {0}.\n", Method1() || Method2());
// In Example #2, method Divisible returns True if the
// first argument is evenly divisible by the second, and False
// otherwise. Using the | operator instead of the || operator
// causes a divide-by-zero exception.
// The following line displays True, because 42 is evenly
// divisible by 7.
Console.WriteLine("Divisible returns {0}.", Divisible(42, 7));
// The following line displays False, because 42 is not evenly
// divisible by 5.
Console.WriteLine("Divisible returns {0}.", Divisible(42, 5));
// The following line displays False when method Divisible
// uses ||, because you cannot divide by 0.
// If method Divisible uses | instead of ||, this line
// causes an exception.
Console.WriteLine("Divisible returns {0}.", Divisible(42, 0));
}
}
/*
Output:
Regular OR:
Method1 called.
Method2 called.
Result is True.
Short-circuit OR:
Method1 called.
Result is True.
Divisible returns True.
Divisible returns False.
Divisible returns False.
*/