如何在 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!

更新日期:20-Jun-2020

271 次瀏覽

開啟你的職業之旅

完成課程即可獲得認證

開始學習
廣告
© . All rights reserved.