C# 中"is"关键字有什么用?

csharpserver side programmingprogramming更新于 2025/10/2 13:07:17

"is" 关键字用于检查对象是否可以转换为特定类型。该操作的返回类型为布尔值。

示例

using System;
namespace DemoApplication{
   class Program{
      static void Main(){
         Employee emp = new PermanentEmployee{
            ID = 1,
            Name = "Martin"
         };
          // 返回 true,因为派生类型可以转换为基类型。
         if (emp is Employee){
            Console.WriteLine(emp.Name + " is Employee");
         }
            else{
            Console.WriteLine(emp.Name + " is not Employee");
         }
          //返回 true,因为实际对象属于 PermanentEmployee 类型.
         if (emp is PermanentEmployee){
            Console.WriteLine(emp.Name + " is PermanentEmployee");
         }
         else{
            Console.WriteLine(emp.Name + " is not PermanentEmployee");
         }
         //返回 false,因为 PermanentEmployee 对象无法转换为
         //ContractEmployee。
         if (emp is ContractEmployee){
            Console.WriteLine(emp.Name + " is ContractEmployee");
         }
         else{
            Console.WriteLine(emp.Name + " is not ContractEmployee");
         }
      }
   }
   class Employee{
      public int ID { get; set; }
      public string Name { get; set; }
   }
   class PermanentEmployee : Employee{
      public int AnnualSalary { get; set; }
   }
   class ContractEmployee : Employee{
      public int HourlySalary { get; set; }
   }
}

相关文章