到目前為止我們已經了解很多關於運算執行的功能,但經常會有一些相關的瑣碎操作需要處理,例如:執行一些建立物件、 檢查執行階段型別物件,轉換物件型別,取得型別的類型、大小…之類的動作會使用的關鍵字。有了這些關鍵字輔助可以幫助運算。
- as:
as 運算子是一種轉型運算,如果無法進行轉換,則傳回 null。static void Main() { object[] objArray = new object[4]; objArray[0] = 1; objArray[1] = 12.3; objArray[2] = "hello"; objArray[3] = null; for (int i = 0; i < objArray.Length; ++i) { string s = objArray[i] as string; if (s != null) { Console.WriteLine(s); } else { Console.WriteLine("not a string"); } } }
- is:
is 關鍵字會判斷物件是否可轉換成指定的類型,成立回傳 true 否則回傳 false。int a; float b; object c; void Main () { print(a is int);//true print(b is int);//false print(c is int);//false c = 1; print(c is int);//true }
- new:
new 關鍵字可當做運算子、修飾詞或條件約束用。
運算中的用法:int i = new int(); //同等於 int i = 0;
用於修飾詞時,new 修飾詞會以相同名稱建立新成員,並隱藏原始成員。若要使用條件約束,型別不能為抽象。
- sizeof:
用來取得類型的大小 (位元組)。int intSize = sizeof(int);
運算式 常數值 sizeof(sbyte)
1 sizeof(byte)
1 sizeof(short)
2 sizeof(ushort)
2 sizeof(int)
4 sizeof(uint)
4 sizeof(long)
8 sizeof(ulong)
8 sizeof(char)
2 (Unicode) sizeof(float)
4 sizeof(double)
8 sizeof(decimal)
16 sizeof(bool)
1 - typeOf:
用來取得類型的 System.Type 物件。兩例子如下,也可以直接使用GetType()方法來取得。System.Type type = typeof(int);
int i = 0; System.Type type = i.GetType();
- true、false:
多載 true 和 false 運算子的類型可用於 if、do、while 、for 陳述式及 條件運算式 ( ? : ) 回傳兩個值的其中一個。bool a = true; Console.WriteLine( a ? "是" : "否" );
- stackalloc:
就像 C 執行階段程式庫中的 _alloca。因為涉及指標類型,所以 stackalloc 於 unsafe 模式用來配置堆疊上的記憶體區塊。int* block = stackalloc int[1];
- nameof:
用來取得變數、類型或成員的名稱。(C# 6 之後可用)WriteLine(nameof(Test.ABC)); // prints "ABC”