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.