C#其它運算符
由C#支持的還有其他一些重要的運算符,包括sizeof,typeof運算和? :。
運算符 | 描述 | 示例 |
---|---|---|
sizeof() | 返回一個數據類型的大小 | sizeof(int), 將返回 4. |
typeof() | 返回一個類的類型 | typeof(StreamReader); |
& | 返回一個變量的地址 | &a; 將給出變量的實際地址 |
* | 指針的變量 | *a; 將指向一個變量 |
? : | 條件表達式 | 如果條件為 true ? 那麼為值 X : 否則為值 Y |
is | 判斷一個對象是否是特定的類型 | If( Ford is Car) // checks if Ford is an object of the Car class. |
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