as(C# 참조)

업데이트: 2007년 11월

as 연산자는 호환되는 참조 형식 간에 특정 형식의 변환을 수행하는 데 사용됩니다. 예를 들면 다음과 같습니다.

   class csrefKeywordsOperators
   {
       class Base
       {
           public override string  ToString()
           {
                 return "Base";
           }
       }
       class Derived : Base 
       { }

       class Program
       {
           static void Main()
           {

               Derived d = new Derived();

               Base b = d as Base;
               if (b != null)
               {
                   Console.WriteLine(b.ToString());
               }

           }
       }
   }

설명

as 연산자는 캐스트 연산과 비슷합니다. 그러나 변환이 불가능한 경우 as는 예외를 발생시키는 대신 null을 반환합니다. 다음 예제를 참조하십시오.

expression as type

이 예제는 expression이 한 번만 계산된다는 점을 제외하고는 다음 식과 같습니다.

expression is type ? (type)expression : (type)null

as 연산자는 오직 참조 변환과 boxing 변환만을 수행합니다. as 연산자는 사용자 정의 변환과 같은 다른 변환을 수행할 수 없습니다. 사용자 정의 변환은 이 연산자 대신 캐스트 식을 사용하여 수행해야 합니다.

예제

class ClassA { }
class ClassB { }

class MainClass
{
    static void Main()
    {
        object[] objArray = new object[6];
        objArray[0] = new ClassA();
        objArray[1] = new ClassB();
        objArray[2] = "hello";
        objArray[3] = 123;
        objArray[4] = 123.4;
        objArray[5] = null;

        for (int i = 0; i < objArray.Length; ++i)
        {
            string s = objArray[i] as string;
            Console.Write("{0}:", i);
            if (s != null)
            {
                Console.WriteLine("'" + s + "'");
            }
            else
            {
                Console.WriteLine("not a string");
            }
        }
    }
}
/*
Output:
0:not a string
1:not a string
2:'hello'
3:not a string
4:not a string
5:not a string
*/

C# 언어 사양

자세한 내용은 C# 언어 사양의 다음 단원을 참조하십시오.

  • 6 변환

  • 7.9.11 as 연산자

참고 항목

개념

C# 프로그래밍 가이드

참조

C# 키워드

is(C# 참조)

?: 연산자(C# 참조)

연산자 키워드(C# 참조)

기타 리소스

C# 참조