C# 中“as”運算子的作用是什麼?


“as”運算子執行相容型別之間的轉換。它就像一個強制型別轉換操作,而且只執行引用轉換、可空轉換和裝箱轉換。as 運算子無法執行其他轉換,例如應由強制型別轉換表示式執行的使用者定義轉換。

以下示例演示了在 C# 中使用 as 操作。在此處,as 用於轉換。

string s = obj[i] as string;

嘗試執行以下程式碼,以便在 C# 中使用“as”運算子。

示例

 即時演示

using System;
public class Demo {
   public static void Main() {
      object[] obj = new object[2];
      obj[0] = "jack";
      obj[1] = 32;
      for (int i = 0; i < obj.Length; ++i) {
         string s = obj[i] as string;
         Console.Write("{0}: ", i);
         if (s != null)
         Console.WriteLine("'" + s + "'");
         else
         Console.WriteLine("This is not a string!");
      }
      Console.ReadKey();
   }
}

輸出

0: 'jack'
1: This is not a string!

更新於: 2020 年 6 月 23 日

136 次瀏覽

開啟您的 職業

完成課程獲得認證

立即開始
廣告
© . All rights reserved.