Computer >> 컴퓨터 >  >> 프로그램 작성 >> C#

C#에서 is 키워드의 용도는 무엇입니까?


"이다" 키워드는 개체를 특정 유형으로 캐스팅할 수 있는지 확인하는 데 사용됩니다. 연산의 반환 유형은 부울입니다.

예시

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; }
   }
}