IS 연산자
C#의 "is" 연산자는 개체의 런타임 형식이 지정된 형식과 호환되는지 여부를 확인합니다.
다음은 구문입니다 -
expr is type
여기, expr 표현입니다
유형 유형의 이름입니다.
다음은 C# &minis;
에서 is 연산자의 사용법을 보여주는 예입니다.예시
using System;
class One { }
class Two { }
public class Demo {
public static void Test(object obj) {
One x;
Two y;
if (obj is One) {
Console.WriteLine("Class One");
x = (One)obj;
} else if (obj is Two) {
Console.WriteLine("Class Two");
y = (Two)obj;
} else {
Console.WriteLine("None of the classes!");
}
}
public static void Main() {
One o1 = new One();
Two t1 = new Two();
Test(o1);
Test(t1);
Test("str");
Console.ReadKey();
}
} 출력
Class One Class Two None of the classes!
AS 연산자
"as" 연산자는 호환되는 유형 간의 변환을 수행합니다. 캐스트 작업과 같으며 참조 변환, nullable 변환 및 boxing 변환만 수행합니다. as 연산자는 사용자 정의 변환과 같은 다른 변환을 수행할 수 없으며 대신 캐스트 표현식을 사용하여 수행해야 합니다.
다음은 C#에서 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!