자바스크립트를 허용해주세요.
[ 자바스크립트 활성화 방법 ]
from Mohon Aktifkan Javascript!
 

[C#] 16장 패턴일치 심화

728x90

✅ 1. switch 표현식 (Switch Expressions)

C# 8버전 부터 추가된 기능으로, 기존 switch 문보다 간결하고 표현력이 좋은 기능입니다. 값을 직접 변환하거나 패턴일치를 조합하면 더욱 좋아집니다.

using System;

class Program
{
    static void Main()
    {
        object obj = 5.54;

        // switch 표현식 호출
        string typeDescription = GetTypeDescription(obj);
        Console.WriteLine(typeDescription);
    }

    // switch 표현식 method
    static string GetTypeDescription(object obj) =>
     obj switch
     {
         int i => $"정수: {i}",
         string s => $"문자열: {s}",
         double c => $"소수점: {c}",
         _ => "알 수 없는 타입입니다."
     };
}
  • obj switch { ... } -> obj값에 따라 어떠한 문자열을 반환할지 결정함.
  • int i => ... -> obj가 i에 값을 담고 반환
  • string s => ... -> obj가 string 이면 s에 값을 담고 반환.
  • null => ... -> null 값이면 "null"값 반환
  • _ => ... -> 아무 조건도 안 맞으면 디폴트 처리

✅ 2. is not

using System;

class Program
{
    static void Main()
    {
        object value = 123;

        if (value is not string)
        {
            Console.WriteLine("문자열이 아님");
        }
    }
}
  • value is not string -> value 가 string이 아니면 true 
  • 여기서 value 가 123(int)이므로 조건 만족

✅ 3.when 절 

using System;

class Program
{
    static void Main()
    {
        Console.WriteLine(GetPersonType(-1));
        Console.WriteLine(GetPersonType(0));
        Console.WriteLine(GetPersonType(5));
    }

    static string GetPersonType(int number) =>
        number switch
        {
            int n when n < 0 => "궁수",
            0 => "전사",
            int n when n > 0 => "마법사",
            _ => "캐릭터 없음"
        };
}
  • when 절은 패턴이 맞은 뒤 조건까지 맞아야 실행됨
  • -1 -> 음수니까 "궁수"
  • 0 -> 상수 패턴 0에 매칭 "전사"
  • 5 -> n > 0 조건 성립 "마법사"

 

 

Csharp-posting/Ch.3 at main · Koras02/Csharp-posting

https://thinky.tistory.com/category/%EA%B2%8C%EC%9E%84%20%EB%AA%A8%EB%94%A9/C%23 - Koras02/Csharp-posting

github.com

 

728x90
LIST