Favicon

Logical patterns

Peponi1/8/20253m

C#
SyntaxKeywordPatternnotandor

1. Introduction

다음 C# 식과 문은 패턴을 지원한다.

여기서는 각 패턴을 조합할 수 있는 논리 패턴을 설명한다.

2. 부정 패턴

not 패턴은 지정된 식의 논리를 부정하여 계산하고 참일 시 true를 반환한다.

private static void Main(string[] args)
{
    int? foo = 7;
 
    Print(foo);
 
    foo = null;
 
    Print(foo);
}
 
private static void Print(int? value)
{
    if (value is int) Console.WriteLine("value is int");
    else if (value is not int) Console.WriteLine("value is not int");
}
 
/* output:
value is int
value is not int
*/

3. 결합 패턴

and 패턴은 지정된 모든 식이 일치하는 경우 true를 반환한다.

int foo = 7;
 
Console.WriteLine(foo switch
{
    < 0 => "foo < 0",
    > 0 and < 5 => "0 < foo < 5",
    > 5 and < 10 => "5 < foo < 10",
    _ => string.Empty
});
 
/* output:
5 < foo < 10
*/

4. 분리 패턴

or 패턴은 지정된 식 중 하나가 일치하는 경우 true를 반환한다.

int foo = 7;
string writeString = string.Empty;
 
switch (foo)
{
    case 1 or 2 or 3:
        writeString = "foo is one of 1, 2, 3";
        break;
 
    case < 0 or > 10:
        writeString = "foo < 0 or foo > 10";
        break;
 
    case > 5 or < 10:
        writeString = "5 < foo < 10";
        break;
}
 
Console.WriteLine(writeString);
 
/* output:
5 < foo < 10
*/

5. 패턴 우선 순위

패턴 조합은 다음 우선 순위에 따라 정렬되며 괄호 ( ) 를 이용해 우선 순위를 지정할 수 있다.

  1. not
  2. and
  3. or
int? foo = 7;
 
if (foo is < 5 and not 7 or > 1)
    Console.WriteLine(foo);
else
    Console.WriteLine("Not matched");
 
/* output:
7
*/

위 예제에서 괄호를 사용하여 우선 순위를 바꾸면 다음 결과를 얻을 수 있다.

int? foo = 7;
 
if (foo is < 5 and (not 7 or > 1))
    Console.WriteLine(foo);
else
    Console.WriteLine("Not matched");
 
/* output:
Not matched
*/

6. 참조 자료