首页  >  文章  >  后端开发  >  C# 中“is”关键字有什么用?

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

WBOY
WBOY转载
2023-09-04 19:09:03729浏览

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

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

示例

using System;
namespace DemoApplication{
   class Program{
      static void Main(){
         Employee emp = new PermanentEmployee{
            ID = 1,
            Name = "Martin"
         };
         // Returns true as the derived type can be converted to base type.
         if (emp is Employee){
            Console.WriteLine(emp.Name + " is Employee");
         }
         else{
            Console.WriteLine(emp.Name + " is not Employee");
         }
         //Returns true, as the actual object is of type PermanentEmployee.
         if (emp is PermanentEmployee){
            Console.WriteLine(emp.Name + " is PermanentEmployee");
         }
         else{
            Console.WriteLine(emp.Name + " is not PermanentEmployee");
         }
         //Returns false, as PermanentEmployee object cannot be converted to
         //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; }
   }
}

以上是C# 中“is”关键字有什么用?的详细内容。更多信息请关注PHP中文网其他相关文章!

声明:
本文转载于:tutorialspoint.com。如有侵权,请联系admin@php.cn删除