"as" 연산자는 호환되는 유형 간의 변환을 수행합니다. 캐스트 작업과 같으며 참조 변환, nullable 변환 및 boxing 변환만 수행합니다. as 연산자는 사용자 정의 변환과 같은 다른 변환을 수행할 수 없으며 대신 캐스트 표현식을 사용하여 수행해야 합니다.
다음은 C#에서 as 연산의 사용법을 보여주는 예입니다. 여기에서 as가 변환에 사용됩니다.
string s = obj[i] as string;
C#에서 'as' 연산자를 사용하려면 다음 코드를 실행해 보세요.
예시
using System;
public class Demo {
public static void Main() {
object[] obj = new object[2];
obj[0] = "jack";
obj[1] = 32;
for (int i = 0; i < obj.Length; ++i) {
string s = obj[i] as string;
Console.Write("{0}: ", i);
if (s != null)
Console.WriteLine("'" + s + "'");
else
Console.WriteLine("This is not a string!");
}
Console.ReadKey();
}
} 출력
0: 'jack' 1: This is not a string!