as 運算子就像是轉型作業,可為 Null的型別之間的型別轉換,如果無法轉換的話, 則會傳回 null 不會引發例外狀況。
class ClassA { } class ClassB { } class MyClass { static void Main() { object[] objArray = new object[6]; objArray[0] = new ClassA(); objArray[1] = new ClassB(); objArray[2] = "hello"; objArray[3] = 123; objArray[4] = 123.4; objArray[5] = null; for (int i = 0; i < objArray.Length; ++i) { string s = objArray[i] as string; if (s != null) { Debug.Log(s); } else { Debug.Log("nostring"); } } } }
則輸出
nostring nostring hello nostring nostring nostring