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.