C# 中的 IS 與 AS 運算子


IS 運算子

C# 中的“is”運算子用於檢查物件的執行時型別是否與給定型別相容。

以下為語法 −

expr is type

其中,expr 為表示式

type 為型別的名稱

以下示例展示如何使用 C# 中的 is 運算子 &minis;

示例

 線上演示

using System;

class One { }
class Two { }

public class Demo {
   public static void Test(object obj) {
      One x;
      Two y;

      if (obj is One) {
         Console.WriteLine("Class One");
         x = (One)obj;
      } else if (obj is Two) {
         Console.WriteLine("Class Two");
         y = (Two)obj;
      } else {
         Console.WriteLine("None of the classes!");
      }
   }

   public static void Main() {
      One o1 = new One();
      Two t1 = new Two();
      Test(o1);
      Test(t1);
      Test("str");
      Console.ReadKey();
   }
}

輸出

Class One
Class Two
None of the classes!

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-20

902 次瀏覽

開啟您的 職業生涯

透過完成課程獲得認證

開始
廣告
© . All rights reserved.