Share via


as(C# 참조)

사용할 수 있는 as 특정 형식의 호환 되는 참조 형식 간에 변환 수행 하는 연산자 또는 nullable 형식을.다음 코드에서는 이러한 예제를 보여 줍니다.


   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 참조 변환, nullable 변환 및 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# 언어 사양을 참조하십시오. 이 언어 사양은 C# 구문 및 사용법에 대한 신뢰할 수 있는 소스입니다.

참고 항목

참조

C# 키워드

is(C# 참조)

?: 연산자(C# 참조)

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

개념

C# 프로그래밍 가이드

기타 리소스

C# 참조