C# - 雜項運算子



C# 支援一些其他重要的運算子,包括sizeof? :

運算子 描述 示例
sizeof() 返回資料型別的尺寸。 sizeof(int),返回 4。
typeof() 返回類的型別。 typeof(StreamReader);
& 返回變數的地址。 &a; 返回變數的實際地址。
* 指向變數的指標。 *a; 建立名為 'a' 的指向變數的指標。
? : 條件表示式 如果條件為真 ? 則值為 X : 否則值為 Y
is 確定物件是否為特定型別。 If( Ford is Car) // 檢查 Ford 是否是 Car 類的物件。
as 強制轉換,如果轉換失敗則不丟擲異常。 Object obj = new StringReader("Hello");

StringReader r = obj as StringReader;

示例

using System;

namespace OperatorsAppl {

   class Program {
   
      static void Main(string[] args) {
         /* example of sizeof operator */
         Console.WriteLine("The size of int is {0}", sizeof(int));
         Console.WriteLine("The size of short is {0}", sizeof(short));
         Console.WriteLine("The size of double is {0}", sizeof(double));
         
         /* example of ternary operator */
         int a, b;
         a = 10;
         b = (a == 1) ? 20 : 30;
         Console.WriteLine("Value of b is {0}", b);

         b = (a == 10) ? 20 : 30;
         Console.WriteLine("Value of b is {0}", b);
         Console.ReadLine();
      }
   }
}

當以上程式碼被編譯和執行時,會產生以下結果:

The size of int is 4
The size of short is 2
The size of double is 8
Value of b is 30
Value of b is 20
csharp_operators.htm
廣告

© . All rights reserved.