邏輯(布爾型)運算子用於對boolean型的結果的運算式進行運算,運算的結果都是boolean型。其運算結果如下所示:
運算子 運算 例子 結果
& AND(與) false&true false
| OR(或) false|true true
^ XOR(異或) false^true true
! NOT(非) !false true
&& AND(短路) false&&true false
|| OR(短路) false||true true
下面對一些比較容易出現問題進行簡單解釋:
1、“^“ 將計算運算元的邏輯“異或”;也就是說,若且唯若只有一個運算元為 true時,結果才為true。
2、“&”與”&&“的區別在於,如果使用前者串連,那麼無論任何情況下,“&”兩邊的運算式都會參與計算。如果使用後者串連,當“&&”的左邊為false,則將不會計算其右邊的運算式。
3、“|”與“||”的區別在於,“|”表示兩邊任何一個布林運算式為真,該組合就會返回true值;而對於“||”,跟第二差不多,若左邊是true則返回true,若左邊是falsh,則看右邊,若右邊為true則為true否則為falsh。
例
| 代碼如下 |
複製代碼 |
using System; using System.Data; using System.Configuration; using System.Web; using System.Web.Security; using System.Web.UI; using System.Web.UI.WebControls; using System.Web.UI.WebControls.WebParts; using System.Web.UI.HtmlControls; public partial class _Default : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { int x = 0; string name = "搜尋吧"; //&運算,兩個中任何一個為假時則為假 Response.Write("x != 0 & name = /"搜尋吧/"的運算結果是:"+ (x != 0 & name == "搜尋吧")); Response.Write("<br>"); //|運算,當兩個中任何一個為真時,運算結果為真,否則為加 Response.Write("x != 0 | name = /"搜尋吧/"的運算結果是:" + (x != 0 | name == "搜尋吧")); Response.Write("<br>"); //^運算,若且唯若有一個是True時,為真,否則為假 Response.Write("x != 0 ^ name = /"搜尋吧/"的運算結果是:" + (x != 0 ^ name == "搜尋吧")); Response.Write("<br>"); Response.Write("x == 0 ^ name = /"搜尋吧/"的運算結果是:" + (x == 0 ^ name == "搜尋吧")); Response.Write("<br>"); //!運算,若真則假,若假則真 Response.Write("x != 0 的運算結果是:" + !(x != 0)); Response.Write("<br>"); //&&短路運算,若左邊為假則退出,若左邊為真,則看右邊 Response.Write("x != 0 && name = /"搜尋吧/"的運算結果是:" + (x != 0 && name == "搜尋吧")); Response.Write("<br>"); //||短路運算,若左邊為真,則為真退出;若左邊為假,則看右邊,右邊為真,則為真,否則為假 Response.Write("x != 0 || name = /"搜尋吧/"的運算結果是:" + (x != 0 || name == "搜尋吧")); } } |
運算子
C# 提供大量運算子,這些運算子是指定在運算式中執行哪些操作的符號。通常允許對枚舉進行整型運算,例如 ==、!=、<、>、<=、>=、binary +、binary -、^、&、|、~、++、-- 和 sizeof()。此外,很多運算子可被使用者重載,由此在應用到使用者定義的類型時更改這些運算子的含義。
| 運算子類別 |
運算子 |
|
基本
|
x.y
f(x)
a[x]
x++
x--
new
typeof
checked
unchecked
->
|
|
一元
|
+
-
!
~
++x
--x
(T)x
True
False
&
sizeof
|
|
乘法
|
*
/
%
|
|
加法
|
+
-
|
|
變換
|
<<
>>
|
|
關係和類型檢測
|
<
>
<=
>=
is
as
|
|
相等
|
==
!=
|
|
邏輯“與”
|
&
|
|
邏輯 XOR
|
^
|
|
邏輯“或”
|
|
|
|
條件 AND
|
&&
|
|
條件 OR
|
||
|
|
條件運算
|
?:
|
|
賦值
|
=
+=
-=
*=
/=
%=
&=
|=
^=
<<=
>>=
??
|
- 運算子優先順序
- 前++ 前-- +(正號) -(負號)! ~
- * / %
- + -
- << >>
- < > <= >=
- == !=
- &
- ^
- |
- &&
- ||
- 賦值運算
- 後++ 後--
C# 允許使用者定義的類型通過使用 operator 關鍵字定義靜態成員函數來重載運算子。但不是所有的運算子都可被重載,下表列出了不能被重載的運算子:
| 運算子 |
可重載性 |
|
+、-、!、~、++、--、true 和 false
|
可以重載這些一元運算子。
|
|
+, -, *, /, %, &, |, ^, <<, >>
|
可以重載這些二進位運算子。
|
|
==, !=, <, >, <=, >=
|
比較子可以重載(但請參見本表後面的說明)。
|
|
&&, ||
|
條件邏輯運算子不能重載,但可使用能夠重載的
& 和
| 進行計算。
|
|
[]
|
不能重載數組索引運算子,但可定義索引器。
|
|
()
|
不能重載轉換運算子,但可定義新的轉換運算子(請參見 explicit 和 implicit)。
|
|
+=, -=, *=, /=, %=, &=, |=, ^=, <<=, >>=
|
賦值運算子不能重載,但
+= 可使用
+ 計算,等等。
|
|
=、.、?:、->、new、is、sizeof 和 typeof
|
不能重載這些運算子。
|
public static Complex operator +(Complex c1, Complex c2) |