<ruby id="bdb3f"></ruby>

    <p id="bdb3f"><cite id="bdb3f"></cite></p>

      <p id="bdb3f"><cite id="bdb3f"><th id="bdb3f"></th></cite></p><p id="bdb3f"></p>
        <p id="bdb3f"><cite id="bdb3f"></cite></p>

          <pre id="bdb3f"></pre>
          <pre id="bdb3f"><del id="bdb3f"><thead id="bdb3f"></thead></del></pre>

          <ruby id="bdb3f"><mark id="bdb3f"></mark></ruby><ruby id="bdb3f"></ruby>
          <pre id="bdb3f"><pre id="bdb3f"><mark id="bdb3f"></mark></pre></pre><output id="bdb3f"></output><p id="bdb3f"></p><p id="bdb3f"></p>

          <pre id="bdb3f"><del id="bdb3f"><progress id="bdb3f"></progress></del></pre>

                <ruby id="bdb3f"></ruby>

                ThinkChat2.0新版上線,更智能更精彩,支持會話、畫圖、視頻、閱讀、搜索等,送10W Token,即刻開啟你的AI之旅 廣告
                # C# 運算符 > 原文: [https://zetcode.com/lang/csharp/operators/](https://zetcode.com/lang/csharp/operators/) 在 C# 教程的這一部分中,我們將討論運算符。 表達式是根據操作數和運算符構造的。 表達式的運算符指示將哪些運算應用于操作數。 表達式中運算符的求值順序由運算符的優先級和關聯性確定 運算符是特殊符號,表示已執行某個過程。 編程語言的運算符來自數學。 程序員處理數據。 運算符用于處理數據。 操作數是運算符的輸入(參數)之一。 ## C# 運算符列表 下表顯示了 C# 語言中使用的一組運算符。 | 類別 | 符號 | | --- | --- | | 符號運算符 | `+ -` | | 算術 | `+ - * / %` | | 邏輯(布爾和按位) | `& &#124; ^ ! ~ && &#124;&#124; true false` | | 字符串連接 | `+` | | 遞增,遞減 | `++ --` | | 移位 | `<< >>` | | 關系 | `== != < > <= >=` | | 賦值 | `= += -= *= /= %= &= &#124;= ^= ??= <<= >>=` | | 成員訪問 | `. ?.` | | 索引 | `[] ?[]` | | 調用 | `()` | | 三元 | `?:` | | 委托連接和刪除 | `+ -` | | 對象創建 | `new` | | 類型信息 | `as is sizeof typeof` | | 異常控制 | `checked unchecked` | | 間接地址 | `* -> [] &` | | Lambda | `=>` | 一個運算符通常有一個或兩個操作數。 那些僅使用一個操作數的運算符稱為一元運算符。 那些使用兩個操作數的對象稱為二進制運算符。 還有一個三元運算符`?:`,它可以處理三個操作數。 某些運算符可以在不同的上下文中使用。 例如+運算符。 從上表中我們可以看到它在不同情況下使用。 它添加數字,連接字符串或委托; 表示數字的符號。 我們說運算符是重載。 ## C# 一元運算符 C# 一元運算符包括:+,-,++,-,強制轉換運算符()和否定!。 ### C# 符號運算符 有兩個符號運算符:`+`和`-`。 它們用于指示或更改值的符號。 `Program.cs` ```cs using System; namespace MinusSign { class Program { static void Main(string[] args) { Console.WriteLine(2); Console.WriteLine(+2); Console.WriteLine(-2); } } } ``` `+`和`-`符號指示值的符號。 加號可以用來表示我們有一個正數。 可以將其省略,并且通常可以這樣做。 `Program.cs` ```cs using System; public class MinusSign { static void Main() { int a = 1; Console.WriteLine(-a); Console.WriteLine(-(-a)); } } ``` 減號更改值的符號。 ```cs $ dotnet run -1 1 ``` 這是輸出。 ### C# 增減運算符 將值遞增或遞減一個是編程中的常見任務。 C# 為此有兩個方便的運算符:`++`和`--`。 ```cs x++; x = x + 1; ... y--; y = y - 1; ``` 上面兩對表達式的作用相同。 `Program.cs` ```cs using System; namespace IncrementDecrement { class Program { static void Main(string[] args) { int x = 6; x++; x++; Console.WriteLine(x); x--; Console.WriteLine(x); } } } ``` 在上面的示例中,我們演示了兩個運算符的用法。 ```cs int x = 6; x++; x++; ``` 將`x`變量初始化為 6。然后將`x`遞增兩次。 現在變量等于 8。 ```cs x--; ``` 我們使用減量運算符。 現在變量等于 7。 ```cs $ dotnet run 8 7 ``` ### C# 顯式強制轉換運算符 顯式強制轉換運算符()可用于將一個類型強制轉換為另一個類型。 請注意,此運算符僅適用于某些類型。 `Program.cs` ```cs using System; namespace CastOperator { class Program { static void Main(string[] args) { float val = 3.2f; int num = (int) val; System.Console.WriteLine(num); } } } ``` 在該示例中,我們將`float`類型顯式轉換為`int`。 ### 求反運算符 取反運算符(!)反轉其操作數的含義。 `Program.cs` ```cs using System; namespace Negation { class Program { static void Main(string[] args) { var isValid = false; if (!isValid) { Console.WriteLine("The option is not valid"); } } } } ``` 在該示例中,我們建立了一個否定條件:如果表達式的逆數有效,則執行該條件。 ## C# 賦值運算符 賦值運算符`=`將值賦給變量。 變量是值的占位符。 在數學中,`=`運算符具有不同的含義。 在等式中,`=`運算符是一個相等運算符。 等式的左側等于右側。 ```cs int x = 1; ``` 在這里,我們為`x`變量分配一個數字。 ```cs x = x + 1; ``` 先前的表達式在數學上沒有意義。 但這在編程中是合法的。 該表達式將`x`變量加 1。 右邊等于 2,并且 2 分配給`x`。 ```cs 3 = x; ``` 此代碼示例導致語法錯誤。 我們無法為字面值分配值。 ## C# 連接字符串 +運算符還用于連接字符串。 `Program.cs` ```cs using System; namespace Concatenate { class Program { static void Main(string[] args) { Console.WriteLine("Return " + "of " + "the king."); } } } ``` 我們使用字符串連接運算符將三個字符串連接在一起。 ```cs $ dotnet run Return of the king. ``` 這是該計劃的結果。 ## C# 算術運算符 下表是 C# 中的算術運算符表。 | 符號 | 名稱 | | --- | --- | | `+` | 加法 | | `-` | 減法 | | `*` | 乘法 | | `/` | 除法 | | `%` | 余數 | 以下示例顯示了算術運算。 `Project.cs` ```cs using System; namespace Arithmetic { class Program { static void Main(string[] args) { int a = 10; int b = 11; int c = 12; int add = a + b + c; int sb = c - a; int mult = a * b; int div = c / 3; int rem = c % a; Console.WriteLine(add); Console.WriteLine(sb); Console.WriteLine(mult); Console.WriteLine(div); Console.WriteLine(rem); } } } ``` 在前面的示例中,我們使用加法,減法,乘法,除法和余數運算。 這些都是數學所熟悉的。 ```cs int rem = c % a; ``` `%`運算符稱為余數或模運算符。 它找到一個數除以另一個的余數。 例如`9 % 4`,9 模 4 為 1,因為 4 兩次進入 9 且余數為 1。 ```cs $ dotnet run 33 2 110 4 2 ``` 這是示例的輸出。 接下來,我們將說明整數除法和浮點除法之間的區別。 `Program.cs` ```cs using System; namespace Division { class Program { static void Main(string[] args) { int c = 5 / 2; Console.WriteLine(c); double d = 5 / 2.0; Console.WriteLine(d); } } } ``` 在前面的示例中,我們將兩個數字相除。 ```cs int c = 5 / 2; Console.WriteLine(c); ``` 在這段代碼中,我們完成了整數除法。 除法運算的返回值為整數。 當我們將兩個整數相除時,結果是一個整數。 ```cs double d = 5 / 2.0; Console.WriteLine(d); ``` 如果值之一是`double`或`float`,則執行浮點除法。 在我們的例子中,第二個操作數是雙精度數,因此結果是雙精度數。 ```cs $ dotnet run 2 2.5 ``` 我們看到了程序的結果。 ## C# 布爾運算符 在 C# 中,我們有三個邏輯運算符。 `bool`關鍵字用于聲明布爾值。 | 符號 | 名稱 | | --- | --- | | `&&` | 邏輯與 | | <code>&#124;&#124;</code> | 邏輯或 | | `!` | 否定 | 布爾運算符也稱為邏輯運算符。 `Program.cs` ```cs using System; namespace Boolean { class Program { static void Main(string[] args) { int x = 3; int y = 8; Console.WriteLine(x == y); Console.WriteLine(y > x); if (y > x) { Console.WriteLine("y is greater than x"); } } } } ``` 許多表達式導致布爾值。 布爾值用于條件語句中。 ```cs Console.WriteLine(x == y); Console.WriteLine(y > x); ``` 關系運算符始終導致布爾值。 這兩行分別顯示`false`和`true`。 ```cs if (y > x) { Console.WriteLine("y is greater than x"); } ``` 僅在滿足括號內的條件時才執行`if`語句的主體。 `y > x`返回`true`,因此消息`"y`大于`x"`被打印到終端。 `true`和`false`關鍵字表示 C# 中的布爾字面值。 `Program.cs` ```cs using System; namespace AndOperator { class Program { static void Main(string[] args) { bool a = true && true; bool b = true && false; bool c = false && true; bool d = false && false; Console.WriteLine(a); Console.WriteLine(b); Console.WriteLine(c); Console.WriteLine(d); } } } ``` 示例顯示了邏輯和運算符。 僅當兩個操作數均為`true`時,它的求值結果為`true`。 ```cs $ dotnet run True False False False ``` `True`只產生一個表達式。 如果兩個操作數中的任何一個為`true`,則邏輯或`||`運算符的計算結果為`true`。 `Program.cs` ```cs using System; namespace OrOperator { class Program { static void Main(string[] args) { bool a = true || true; bool b = true || false; bool c = false || true; bool d = false || false; Console.WriteLine(a); Console.WriteLine(b); Console.WriteLine(c); Console.WriteLine(d); } } } ``` 如果運算符的任一側為真,則操作的結果為真。 ```cs $ dotnet run True True True False ``` 四個表達式中的三個表示為`true`。 否定運算符`!`將`true`設為`false`,并將`false`設為`false`。 `Program.cs` ```cs using System; namespace NegationEx { class Program { static void Main(string[] args) { Console.WriteLine(!true); Console.WriteLine(!false); Console.WriteLine(!(4 < 3)); } } } ``` 該示例顯示了否定運算符的作用。 ```cs $ dotnet run False True True ``` 這是`negation.exe`程序的輸出。 `||`和`&&`運算符經過短路求值。 短路求值意味著僅當第一個參數不足以確定表達式的值時,才求值第二個參數:當邏輯的第一個參數的結果為`false`時,總值必須為`false`; 當邏輯或的第一個參數為`true`時,總值必須為`true`。 短路求值主要用于提高性能。 一個例子可以使這一點更加清楚。 `Program.cs` ```cs using System; namespace ShortCircuit { class Program { static void Main(string[] args) { Console.WriteLine("Short circuit"); if (One() && Two()) { Console.WriteLine("Pass"); } Console.WriteLine("#############"); if (Two() || One()) { Console.WriteLine("Pass"); } } public static bool One() { Console.WriteLine("Inside one"); return false; } public static bool Two() { Console.WriteLine("Inside two"); return true; } } } ``` 在示例中,我們有兩種方法。 它們在布爾表達式中用作操作數。 我們將看看它們是否被調用。 ```cs if (One() && Two()) { Console.WriteLine("Pass"); } ``` `One()`方法返回`false`。 短路`&&`不求值第二種方法。 沒有必要。 一旦操作數為`false`,則邏輯結論的結果始終為`false`。 僅將`"Inside one"`打印到控制臺。 ```cs Console.WriteLine("#############"); if (Two() || One()) { Console.WriteLine("Pass"); } ``` 在第二種情況下,我們使用`||`運算符,并使用`Two()`方法作為第一個操作數。 在這種情況下,`"Inside two"`和`"Pass"`字符串將打印到終端。 再次不必求值第二操作數,因為一旦第一操作數求值為`true`,則邏輯或始終為`true`。 ```cs $ ShortCircuit>dotnet run Short circuit Inside one ############# Inside two Pass ``` We see the result of the program. ## C# 關系運算符 關系運算符用于比較值。 這些運算符總是產生布爾值。 | 符號 | 含義 | | --- | --- | | `<` | 小于 | | `<=` | 小于或等于 | | `>` | 大于 | | `>=` | 大于或等于 | | `==` | 等于 | | `!=` | 不等于 | 關系運算符也稱為比較運算符。 `Program.cs` ```cs using System; namespace Relational { class Program { static void Main(string[] args) { Console.WriteLine(3 < 4); Console.WriteLine(3 == 4); Console.WriteLine(4 >= 3); Console.WriteLine(4 != 3); } } } ``` 在代碼示例中,我們有四個表達式。 這些表達式比較整數值。 每個表達式的結果為`true`或`false`。 在 C# 中,我們使用`==`比較數字。 某些語言(例如 Ada,Visual Basic 或 Pascal)使用`=`比較數字。 ## C# 按位運算符 小數對人類是自然的。 二進制數是計算機固有的。 二進制,八進制,十進制或十六進制符號僅是相同數字的符號。 按位運算符使用二進制數的位。 像 C# 這樣的高級語言很少使用按位運算符。 | 符號 | 含義 | | --- | --- | | `~` | 按位取反 | | `^` | 按位異或 | | `&` | 按位與 | | <code>&#124;</code> | 按位或 | 按位取反運算符分別將 1 更改為 0,將 0 更改為 1。 ```cs Console.WriteLine(~ 7); // prints -8 Console.WriteLine(~ -8); // prints 7 ``` 運算符恢復數字 7 的所有位。這些位之一還確定數字是否為負。 如果我們再一次對所有位取反,我們將再次得到 7。 按位,運算符在兩個數字之間進行逐位比較。 僅當操作數中的兩個對應位均為 1 時,位位置的結果才為 1。 ```cs 00110 & 00011 = 00010 ``` 第一個數字是二進制表示法 6,第二個數字是 3,結果是 2。 ```cs Console.WriteLine(6 & 3); // prints 2 Console.WriteLine(3 & 6); // prints 2 ``` 按位或運算符在兩個數字之間進行逐位比較。 如果操作數中的任何對應位為 1,則位位置的結果為 1。 ```cs 00110 | 00011 = 00111 ``` 結果為`00110`或十進制 7。 ```cs Console.WriteLine(6 | 3); // prints 7 Console.WriteLine(3 | 6); // prints 7 ``` 按位互斥或運算符在兩個數字之間進行逐位比較。 如果操作數中對應位中的一個或另一個(但不是全部)為 1,則位位置的結果為 1。 ```cs 00110 ^ 00011 = 00101 ``` 結果為`00101`或十進制 5。 ```cs Console.WriteLine(6 ^ 3); // prints 5 Console.WriteLine(3 ^ 6); // prints 5 ``` ## C# 復合賦值運算符 復合賦值運算符由兩個運算符組成。 他們是速記員。 ```cs a = a + 3; a += 3; ``` `+=`復合運算符是這些速記運算符之一。 以上兩個表達式相等。 將值 3 添加到變量 a 中。 其他復合運算符是: ```cs -= *= /= %= &= |= <<= >>= ``` `Program.cs` ```cs using System; namespace CompoundOperators { class Program { static void Main(string[] args) { int a = 1; a = a + 1; Console.WriteLine(a); a += 5; Console.WriteLine(a); a *= 3; Console.WriteLine(a); } } } ``` 在示例中,我們使用兩個復合運算符。 ```cs int a = 1; a = a + 1; ``` `a`變量被初始化為 1。 使用非速記符號將 1 添加到變量。 ```cs a += 5; ``` 使用`+=`復合運算符,將 5 加到`a`變量中。 該語句等于`a = a + 5;`。 ```cs a *= 3; ``` 使用`*=`運算符,將`a`乘以 3。該語句等于`a = a * 3;`。 ```cs $ dotnet run 2 7 21 ``` 這是示例輸出。 ## C# `new`運算符 `new`運算符用于創建對象和調用構造器。 `Program.cs` ```cs using System; namespace NewOperator { class Being { public Being() { Console.WriteLine("Being created"); } } class Program { static void Main(string[] args) { var b = new Being(); Console.WriteLine(b); var vals = new int[] { 1, 2, 3, 4, 5 }; System.Console.WriteLine(string.Join(" ", vals)); } } } ``` 在示例中,我們使用`new`運算符創建了一個新的自定義對象和一個整數數組。 ```cs public Being() { Console.WriteLine("Being created"); } ``` 這是一個構造器。 在創建對象時調用它。 ```cs $ dotnet run Being created NewOperator.Being 1 2 3 4 5 ``` This is the output. ## C# 訪問運算符 訪問運算符`[]`與數組,索引器和屬性一起使用。 `Program.cs` ```cs using System; using System.Collections.Generic; namespace AccessOperator { class Program { static void Main(string[] args) { var vals = new int[] { 2, 4, 6, 8, 10 }; Console.WriteLine(vals[0]); var domains = new Dictionary<string, string>() { { "de", "Germany" }, { "sk", "Slovakia" }, { "ru", "Russia" } }; Console.WriteLine(domains["de"]); oldMethod(); } [Obsolete("Don't use OldMethod, use NewMethod instead", false)] public static void oldMethod() { Console.WriteLine("oldMethod()"); } public static void newMethod() { Console.WriteLine("newMethod()"); } } } ``` 在該示例中,我們使用`[]`運算符獲取數組的元素,字典對的值,并激活內置屬性。 ```cs var vals = new int[] { 2, 4, 6, 8, 10 }; Console.WriteLine(vals[0]); ``` 我們定義一個整數數組。 我們用`vals[0]`獲得第一個元素。 ```cs var domains = new Dictionary<string, string>() { { "de", "Germany" }, { "sk", "Slovakia" }, { "ru", "Russia" } }; Console.WriteLine(domains["de"]); ``` 創建字典。 使用`domains["de"]`,我們獲得具有`"de"`鍵的貨幣對的值。 ```cs [Obsolete("Don't use OldMethod, use NewMethod instead", false)] public static void oldMethod() { Console.WriteLine("oldMethod()"); } ``` 我們激活了內置的`Obsolete`屬性。 該屬性發出警告。 ```cs $ dotnet run Program.cs(22,13): warning CS0618: 'Program.oldMethod()' is obsolete: 'Don't use OldMethod, use NewMethod instead' [C:\Users\Jano\Documents\csharp\tutorial\AccessOperator\AccessOperator.csproj] 2 Germany oldMethod() ``` This is the output. ## C# 索引的最終運算符`^` 結束運算符^的索引指示從序列結尾開始的元素位置。 例如,`^1`指向序列的最后一個元素,`^n`指向偏移為`length - n`的元素。 `Program.cs` ```cs using System; using System.Linq; namespace IndexFromEnd { class Program { static void Main(string[] args) { int[] vals = { 1, 2, 3, 4, 5 }; Console.WriteLine(vals[^1]); Console.WriteLine(vals[^2]); var word = "gray falcon"; Console.WriteLine(word[^1]); } } } ``` 在示例中,我們將運算符應用于數組和字符串。 ```cs int[] vals = { 1, 2, 3, 4, 5 }; Console.WriteLine(vals[^1]); Console.WriteLine(vals[^2]); ``` 我們打印數組的最后一個元素和最后一個元素。 ```cs var word = "gray falcon"; Console.WriteLine(word[^1]); ``` 我們打印單詞的最后一個字母。 ```cs $ dotnet run 5 4 n ``` This is the output. ## C# 范圍運算符`..` `..`運算符指定索引范圍的開始和結束作為其操作數。 左側操作數是范圍的一個包含范圍的開始。 右側操作數是范圍的排他端。 ```cs x.. is equivalent to x..^0 ..y is equivalent to 0..y .. is equivalent to 0..^0 ``` 可以省略`..`運算符的操作數以獲取開放范圍。 `Program.cs` ```cs using System; namespace RangeOperator { class Program { static void Main(string[] args) { int[] vals = { 1, 2, 3, 4, 5, 6, 7 }; var slice1 = vals[1..4]; Console.WriteLine("[{0}]", String.Join(", ", slice1)); var slice2 = vals[..^0]; Console.WriteLine("[{0}]", String.Join(", ", slice2)); } } } ``` 在示例中,我們使用`..`運算符獲取數組切片。 ```cs var range1 = vals[1..4]; Console.WriteLine("[{0}]", String.Join(", ", range1)); ``` 我們創建一個從索引 1 到索引 4 的數組切片; 最后一個索引 4 不包括在內。 ```cs var slice2 = vals[..^0]; Console.WriteLine("[{0}]", String.Join(", ", slice2)); ``` 在這里,我們基本上創建了數組的副本。 ```cs $ dotnet run [2, 3, 4] [1, 2, 3, 4, 5, 6, 7] ``` This is the output. ## C# 類型信息 現在,我們將關注使用類型的運算符。 `sizeof`運算符用于獲取值類型的字節大小。 `typeof`用于獲取類型的`System.Type`對象。 `Program.cs` ```cs using System; namespace SizeType { class Program { static void Main(string[] args) { Console.WriteLine(sizeof(int)); Console.WriteLine(sizeof(float)); Console.WriteLine(sizeof(Int32)); Console.WriteLine(typeof(int)); Console.WriteLine(typeof(float)); } } } ``` 我們使用`sizeof`和`typeof`運算符。 ```cs $ dotnet run 4 4 4 System.Int32 ``` 我們可以看到`int`類型是`System.Int32`的別名,`float`是`System.Single`類型的別名。 `is`操作符檢查對象是否與給定類型兼容。 `Program.cs` ```cs using System; namespace IsOperator { class Base { } class Derived : Base { } class Program { static void Main(string[] args) { Base _base = new Base(); Derived derived = new Derived(); Console.WriteLine(_base is Base); Console.WriteLine(_base is Object); Console.WriteLine(derived is Base); Console.WriteLine(_base is Derived); } } } ``` 我們根據用戶定義的類型創建兩個對象。 ```cs class Base {} class Derived : Base {} ``` 我們有一個`Base`和`Derived`類。 `Derived`類繼承自`Base`類。 ```cs Console.WriteLine(_base is Base); Console.WriteLine(_base is Object); ``` `Base`等于`Base`,因此第一行顯示`True`。 `Base`也與`Object`類型兼容。 這是因為每個類都繼承自所有類的母體`Object`類。 ```cs Console.WriteLine(derived is Base); Console.WriteLine(_base is Derived); ``` 派生對象與`Base`類兼容,因為它顯式繼承自`Base`類。 另一方面,`_base`對象與`Derived`類無關。 ```cs $ dotnet run True True True False ``` 這是示例的輸出。 `as`運算符用于在兼容的引用類型之間執行轉換。 如果無法進行轉換,則運算符將返回`null`。 與強制轉換操作不同,后者引發異常。 `Program.cs` ```cs using System; namespace AsOperator { class Base { } class Derived : Base { } class Program { static void Main(string[] args) { object[] objects = new object[6]; objects[0] = new Base(); objects[1] = new Derived(); objects[2] = "ZetCode"; objects[3] = 12; objects[4] = 1.4; objects[5] = null; for (int i = 0; i < objects.Length; i++) { string s = objects[i] as string; Console.Write("{0}:", i); if (s != null) { Console.WriteLine(s); } else { Console.WriteLine("not a string"); } } } } } ``` 在上面的示例中,我們使用`as`運算符執行轉換。 ```cs string s = objects[i] as string; ``` 我們嘗試將各種類型轉換為字符串類型。 但只有一次轉換有效。 ```cs $ dotnet run 0:not a string 1:not a string 2:ZetCode 3:not a string 4:not a string 5:not a string ``` This is the output of the example. ## C# 運算符優先級 運算符優先級告訴我們首先求值哪個運算符。 優先級對于避免表達式中的歧義是必要的。 以下表達式 28 或 40 的結果是什么? ```cs 3 + 5 * 5 ``` 像數學中一樣,乘法運算符的優先級高于加法運算符。 結果是 28。 ```cs (3 + 5) * 5 ``` 要更改求值的順序,可以使用括號。 括號內的表達式始終首先被求值。 下表顯示了按優先級排序的通用 C# 運算符(優先級最高): | 運算符 | 類別 | 關聯性 | | --- | --- | --- | | 主要 | `x.y x?.y, x?[y] f(x) a[x] x++ x-- new typeof default checked unchecked` | 左 | | 一元 | `+ - ! ~ ++x --x (T)x` | 左 | | 乘法 | `* / %` | 左 | | 加法 | `+ -` | 左 | | 移位 | `<< >>` | 左 | | 相等 | `== !=` | 右 | | 邏輯與 | `&` | 左 | | 邏輯異或 | `^` | 左 | | 邏輯或 | <code>&#124;</code> | 左 | | 條件與 | `&&` | 左 | | 條件或 | <code>&#124;&#124;</code> | 左 | | 空合并 | `??` | 左 | | 三元 | `?:` | 右 | | 賦值 | `= *= /= %= += -= <<= >>= &= ^= &#124;= ??= =>` | 右 | 表的同一行上的運算符具有相同的優先級。 `Program.cs` ```cs using System; namespace Precedence { class Program { static void Main(string[] args) { Console.WriteLine(3 + 5 * 5); Console.WriteLine((3 + 5) * 5); Console.WriteLine(! true | true); Console.WriteLine(! (true | true)); } } } ``` 在此代碼示例中,我們顯示一些表達式。 每個表達式的結果取決于優先級。 ```cs Console.WriteLine(3 + 5 * 5); ``` 該行打印 28。乘法運算符的優先級高于加法。 首先,計算`5*5`的乘積,然后加 3。 ```cs Console.WriteLine(! true | true); ``` 在這種情況下,否定運算符具有更高的優先級。 首先,將第一個`true`值取反為`false`,然后`|`運算符將`false`和`true`組合在一起,最后給出`true`。 ```cs $ dotnet run 28 40 True False ``` 這是`precedence.exe`程序的結果。 ## C# 關聯規則 有時,優先級不能令人滿意地確定表達式的結果。 還有另一個規則稱為關聯性。 運算符的關聯性確定優先級與相同的運算符的求值順序。 ```cs 9 / 3 * 3 ``` 此表達式的結果是 9 還是 1? 乘法,刪除和模運算符從左到右關聯。 因此,該表達式的計算方式為:`(9 / 3) * 3`,結果為 9。 算術,布爾,關系和按位運算符都是從左到右關聯的。 另一方面,賦值運算符是正確關聯的。 `Program.cs` ```cs using System; namespace Associativity { class Program { static void Main(string[] args) { int a, b, c, d; a = b = c = d = 0; Console.WriteLine("{0} {1} {2} {3}", a, b, c, d); int j = 0; j *= 3 + 1; Console.WriteLine(j); } } } ``` 在該示例中,有兩種情況,其中關聯性規則確定表達式。 ```cs int a, b, c, d; a = b = c = d = 0; ``` 賦值運算符從右到左關聯。 如果關聯性從左到右,則以前的表達式將不可能。 ```cs int j = 0; j *= 3 + 1; ``` 復合賦值運算符從右到左關聯。 我們可能期望結果為 1。但是實際結果為 0。由于有關聯性。 首先求值右邊的表達式,然后應用復合賦值運算符。 ```cs $ dotnet run 0 0 0 0 0 ``` This is the output. ## C# 空條件運算符 空條件運算符僅在該操作數的值為非空時才將成員訪問`?.`或元素訪問 `?[]`應用于其操作數。 如果操作數的值為`null`,則應用運算符的結果為`null`。 `Program.cs` ```cs using System; using System.Collections.Generic; namespace NullConditional { class User { public User() { } public User(string name, string occupation) { this.name = name; this.occupation = occupation; } public string name { get; set; } public string occupation { get; set; } public override string ToString() => $"{name} {occupation}"; } class Program { static void Main(string[] args) { var users = new List<User>() { new User("John Doe", "gardener"), new User(), new User("Lucia Newton", "teacher") }; users.ForEach(user => Console.WriteLine(user.name?.ToUpper())); } } } ``` 在示例中,我們有一個帶有兩個成員的`User`類:`name`和`occupation`。 我們在`?.`運算符的幫助下訪問對象的`name`成員。 ```cs var users = new List<User>() { new User("John Doe", "gardener"), new User(), new User("Lucia Newton", "teacher") }; ``` 我們有一個用戶列表。 其中一個未初始化,因此其成員為`null`。 ```cs users.ForEach(user => Console.WriteLine(user.name?.ToUpper())); ``` 我們使用`?.`訪問`name`成員并調用`ToUpper()`方法。 `?.`通過不調用`null`值上的`ToUpper()`來防止`System.NullReferenceException`。 ```cs $ dotnet run JOHN DOE LUCIA NEWTON ``` This is the output. 在下面的示例中,我們使用`[].`運算符。 `Program.cs` ```cs using System; namespace NullConditional2 { class Program { static void Main(string[] args) { int?[] vals = { 1, 2, 3, null, 4, 5 }; int i = 0; while (i < vals.Length) { Console.WriteLine(vals[i]?.GetType()); i++; } } } } ``` 在此示例中,我們在數組中有一個`null`值。 我們通過在數組元素上應用`[].`運算符來防止`System.NullReferenceException`。 ## C# 空值運算符 空合并運算符`??`用于定義`nullable`類型的默認值。 如果不為`null`,則返回左側操作數;否則返回 0。 否則返回正確的操作數。 當我們使用數據庫時,我們經常處理缺失的值。 這些值在程序中為空。 該運算符是處理此類情況的便捷方法。 `Program.cs` ```cs using System; namespace NullCoalescing { class Program { static void Main(string[] args) { int? x = null; int? y = null; int z = x ?? y ?? -1; Console.WriteLine(z); } } } ``` 空合并運算符的示例程序。 ```cs int? x = null; int? y = null; ``` 兩種可為空的`int`類型被初始化為`null`。 `int?`是`Nullable<int>`的簡寫。 它允許將空值分配給`int`類型。 ```cs int z = x ?? y ?? -1; ``` 我們要為`z`變量分配一個值。 但是它一定不是`null`。 這是我們的要求。 我們可以輕松地為此使用`null`折疊運算符。 如果`x`和`y`變量均為空,我們將 -1 分配給`z`。 ```cs $ dotnet run -1 ``` 這是程序的輸出。 ## C# 空折疊賦值運算符 僅當左側操作數的值為`null`時,空合并賦值運算符`??=`才將其右側操作數的值分配給其左側操作數。 如果`??=`運算符的左手操作數取值為非空,則不計算其右手操作數。 它在 C# 8.0 和更高版本中可用。 `Program.cs` ```cs using System; using System.Collections.Generic; namespace NullCoalescingAssignment { class Program { static void Main(string[] args) { List<int> vals = null; vals ??= new List<int>() {1, 2, 3, 4, 5, 6}; vals.Add(7); vals.Add(8); vals.Add(9); Console.WriteLine(string.Join(", ", vals)); vals ??= new List<int>() {1, 2, 3, 4, 5, 6}; Console.WriteLine(string.Join(", ", vals)); } } } ``` 在該示例中,我們在整數值列表上使用`null`折疊賦值運算符。 ```cs List<int> vals = null; ``` 首先,將列表分配給`null`。 ```cs vals ??= new List<int>() {1, 2, 3, 4, 5, 6}; ``` 我們使用`??=`將新的列表對象分配給變量。 由于它是`null`,因此分配了列表。 ```cs vals.Add(7); vals.Add(8); vals.Add(9); Console.WriteLine(string.Join(", ", vals)); ``` 我們將一些值添加到列表中并打印其內容。 ```cs vals ??= new List<int>() {1, 2, 3, 4, 5, 6}; ``` 我們嘗試為變量分配一個新的列表對象。 由于該變量不再是`null`,因此不會分配該列表。 ```cs $ dotnet run 1, 2, 3, 4, 5, 6, 7, 8, 9 1, 2, 3, 4, 5, 6, 7, 8, 9 ``` This is the output. ## C# 三元運算符 三元運算符`?:`是條件運算符。 對于要根據條件表達式選擇兩個值之一的情況,它是一個方便的運算符。 ```cs cond-exp ? exp1 : exp2 ``` 如果`cond-exp`為`true`,則求值`exp1`并返回結果。 如果`cond-exp`為`false`,則求值`exp2`并返回其結果。 `Program.cs` ```cs using System; namespace Ternary { class Program { static void Main(string[] args) { int age = 31; bool adult = age >= 18 ? true : false; Console.WriteLine("Adult: {0}", adult); } } } ``` 在大多數國家/地區,成年取決于您的年齡。 如果您的年齡超過特定年齡,則您已經成年。 對于三元運算符,這是一種情況。 ```cs bool adult = age >= 18 ? true : false; ``` 首先,對賦值運算符右側的表達式進行求值。 三元運算符的第一階段是條件表達式求值。 因此,如果年齡大于或等于 18,則返回`?`字符后的值。 如果不是,則返回`:`字符后的值。 然后將返回值分配給成人變量。 ```cs $ dotnet run Adult: True ``` 31 歲的成年人是成年人。 ## C# Lambda 運算符 `=>`令牌稱為 lambda 運算符。 它是從函數式語言中提取的運算符。 該運算符可以使代碼更短,更清晰。 另一方面,理解語法可能很棘手。 特別是如果程序員以前從未使用過函數式語言。 只要可以使用委托,我們都可以使用 lambda 表達式。 lambda 表達式的定義是:lambda 表達式是一個匿名函數,可以包含表達式和語句。 左邊是一組數據,右邊是表達式或語句塊。 這些語句應用于數據的每個項目。 在 lambda 表達式中,我們沒有`return`關鍵字。 最后一條語句自動返回。 而且,我們不需要為參數指定類型。 編譯器將猜測正確的參數類型。 這稱為類型推斷。 `Program.cs` ```cs using System; using System.Collections.Generic; namespace LambdaOperator { class Program { static void Main(string[] args) { var list = new List<int>() { 3, 2, 1, 8, 6, 4, 7, 9, 5 }; var subList = list.FindAll(val => val > 3); foreach (int i in subList) { Console.WriteLine(i); } } } } ``` 我們有一個整數列表。 我們打印所有大于 3 的數字。 ```cs var list = new List<int>() { 3, 2, 1, 8, 6, 4, 7, 9, 5 }; ``` 我們有一個通用的整數列表。 ```cs var subList = list.FindAll(val => val > 3); ``` 在這里,我們使用 lambda 運算符。 `FindAll()`方法采用謂詞作為參數。 謂詞是一種特殊的委托,它返回布爾值。 該謂詞適用于列表中的所有項目。 `val`是沒有類型指定的輸入參數。 我們可以明確指定類型,但這不是必需的。 編譯器將期望使用`int`類型。 `val`是列表中的當前輸入值。 比較它是否大于 3 并返回布爾值`true`或`false`。 最后,`FindAll()`將返回所有符合條件的值。 它們被分配給子列表集合。 ```cs foreach (int i in subList) { Console.WriteLine(i); } ``` 子列表集合的項目將打印到終端。 ```cs $ dotnet run 8 6 4 7 9 5 ``` 大于 3 的整數列表中的值。 `Program.cs` ```cs using System; using System.Collections.Generic; namespace AnonymousDelegate { class Program { static void Main(string[] args) { var nums = new List<int>() { 3, 2, 1, 8, 6, 4, 7, 9, 5 }; var nums2 = nums.FindAll( delegate(int i) { return i > 3; } ); foreach (int i in nums2) { Console.WriteLine(i); } } } } ``` 這是相同的例子。 我們使用匿名委托代替 lambda 表達式。 ## C# 計算素數 我們將計算素數。 `Program.cs` ```cs using System; namespace Primes { class Program { static void Main(string[] args) { int[] nums = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28 }; Console.Write("Prime numbers: "); foreach (int num in nums) { if (num == 1) continue; if (num == 2 || num == 3) { Console.Write(num + " "); continue; } int i = (int) Math.Sqrt(num); bool isPrime = true; while (i > 1) { if (num % i == 0) { isPrime = false; } i--; } if (isPrime) { Console.Write(num + " "); } } Console.Write('\n'); } } } ``` 在上面的示例中,我們處理了許多不同的運算符。 質數(或質數)是一個自然數,它具有兩個截然不同的自然數除數:1 和它本身。 我們拾取一個數字并將其除以數字,從 1 到拾取的數字。 實際上,我們不必嘗試所有較小的數字。 我們可以將數字除以所選數字的平方根。 該公式將起作用。 我們使用余數除法運算符。 ```cs int[] nums = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28 }; ``` 我們將從這些數字計算素數。 ```cs if (num == 1) continue; ``` 根據定義,1 不是質數 ```cs if (num == 2 || num == 3) { Console.Write(num + " "); continue; } ``` 我們跳過 2 和 3 的計算,它們是質數。 請注意等式和條件或運算符的用法。 `==`的優先級高于`||`運算符。 因此,我們不需要使用括號。 ```cs int i = (int) Math.Sqrt(num); ``` 如果我們僅嘗試小于所討論數字的平方根的數字,那么我們可以。 ```cs while (i > 1) { ... i--; } ``` 這是一個`while`循環。 `i`是計算出的數字的平方根。 我們使用減量運算符將每個循環周期的`i`減 1。 當`i`小于 1 時,我們終止循環。 例如,我們有 9。9 的平方根是 3。我們將 9 的數字除以 3 和 2。這對于我們的計算就足夠了。 ```cs if (num % i == 0) { isPrime = false; } ``` 這是算法的核心。 如果余數除法運算符對于任何`i`值返回 0,則說明所討論的數字不是質數。 在 C# 教程的這一部分中,我們介紹了 C# 運算符。
                  <ruby id="bdb3f"></ruby>

                  <p id="bdb3f"><cite id="bdb3f"></cite></p>

                    <p id="bdb3f"><cite id="bdb3f"><th id="bdb3f"></th></cite></p><p id="bdb3f"></p>
                      <p id="bdb3f"><cite id="bdb3f"></cite></p>

                        <pre id="bdb3f"></pre>
                        <pre id="bdb3f"><del id="bdb3f"><thead id="bdb3f"></thead></del></pre>

                        <ruby id="bdb3f"><mark id="bdb3f"></mark></ruby><ruby id="bdb3f"></ruby>
                        <pre id="bdb3f"><pre id="bdb3f"><mark id="bdb3f"></mark></pre></pre><output id="bdb3f"></output><p id="bdb3f"></p><p id="bdb3f"></p>

                        <pre id="bdb3f"><del id="bdb3f"><progress id="bdb3f"></progress></del></pre>

                              <ruby id="bdb3f"></ruby>

                              哎呀哎呀视频在线观看