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.