IT_Programming/C#

as 연산자

JJun ™ 2006. 2. 27. 12:18

as연산자도 is연산자와 비슷한 역할을 한다.

 

문장 as 비교할 자료형

as가 is와 다른 점은 형 검사를 한 후

true면 좌 항의 객체에 형 변환한 결과를 반환하고, false라면 null을 반환한다.

 

=============================================================================

 

[ex]

 

using System;

 

interface Imammal
{
 void walk();
}

class Cat : Imammal
{
 public void walk()
 {
  Console.WriteLine("고양이과는 걸을 수 있습니다.");
 }
}

class Lion : Cat, Imammal
{
 public new void walk()
 {
  Console.WriteLine("사자는 걸을 수 있습니다.");
 }
}

class Whoanimal
{
 public static void Main()
 {
  Imammal simba = new Lion();
  object obj1 = simba as Cat;

  if(obj1 != null) // as는 true일 경우 형 변환한 결과값 반환, false 일 경우 null값 반환
   Console.WriteLine("Is Simba a Cat? : {0}", obj1.GetType());
  else
   Console.WriteLine("저는 고양이가 아닌디유~");

  Cat leo = new Cat();
  object obj2 = leo as Lion;

  if(obj2 != null)
   Console.WriteLine("Is Leo a Lion? : {0}", obj2.GetType());
  else
   Console.WriteLine("저는 사자가 아닌디유~");
 }
}

'IT_Programming > C#' 카테고리의 다른 글

프로퍼티  (0) 2006.02.27
배열  (0) 2006.02.27
Is 연산자  (0) 2006.02.27
구조체  (0) 2006.02.27
인터페이스  (0) 2006.02.27