Introduction
- 다음 C# 식과 문은 패턴을 지원한다.
- 여기서는 식 결과가 지정된 상수와 같은지 확인할 수 있는
상수 패턴
을 설명한다.
상수 패턴
에는 상수 형식으로 변환할 수 있는 형식을 사용할 수 있다.
Example
// is 식
int foo = 7;
if (foo is 7) Console.WriteLine("foo is 7");
else Console.WriteLine("foo is not 7");
/* output:
foo is 7
*/
// switch 식
int foo = 7;
Console.WriteLine(foo switch
{
7 => "foo is 7",
_ => "foo is not 7"
});
/* output:
foo is 7
*/
// switch 문
int foo = 7;
string writeString = string.Empty;
switch (foo)
{
case 7:
writeString = "foo is 7";
break;
default:
writeString = "foo is not 7";
break;
}
Console.WriteLine(writeString);
/* output:
foo is 7
*/
public class Foo
{
public static bool operator ==(Foo a, Foo b) => false;
public static bool operator !=(Foo a, Foo b) => false;
}
Foo? foo = null;
if (foo == null) Console.WriteLine("== null");
if (foo is null) Console.WriteLine("is null");
/* output:
is null
*/
참조 자료