卓越飞翔博客卓越飞翔博客

卓越飞翔 - 您值得收藏的技术分享站
技术文章17325本站已运行3326

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

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; }
   }
}
卓越飞翔博客
上一篇: Python程序将字符串拆分为多个子字符串
下一篇: 返回列表
留言与评论(共有 0 条评论)
   
验证码:
隐藏边栏