programing

C # switch 문의 기본 레이블은 nullable 열거 형을 어떻게 처리합니까?

minecode 2021. 1. 15. 07:58
반응형

C # switch 문의 기본 레이블은 nullable 열거 형을 어떻게 처리합니까?


C # switch 문의 기본 레이블은 nullable 열거 형을 어떻게 처리합니까?

기본 레이블이 null 및 처리되지 않은 케이스를 포착합니까?


null이면 기본 레이블에 도달합니다.

public enum YesNo
{
    Yes,
    No,
}

public class Program
{
    public static void Main(string[] args)
    {
        YesNo? value = null;
        switch (value)
        {
            case YesNo.Yes:
                Console.WriteLine("Yes");
                break;
            case YesNo.No:
                Console.WriteLine("No");
                break;
            default:
                Console.WriteLine("default");
                break;
        }
    }
}

프로그램이 인쇄 default됩니다.

null이 처리되지 않는 한.

public class Program
{
    public static void Main(string[] args)
    {
        YesNo? value = null;
        switch (value)
        {
            case YesNo.Yes:
                Console.WriteLine("Yes");
                break;
            case YesNo.No:
                Console.WriteLine("No");
                break;
            case null:
                Console.WriteLine("NULL");
                break;
            default:
                Console.WriteLine("default");
                break;
        }
    }
}

인쇄합니다 NULL.

나중에 추가 된 처리되지 않은 열거 형 값이있는 경우 :

public enum YesNo
{
    Yes,
    No,
    FileNotFound,
}

public class Program
{
    public static void Main(string[] args)
    {
        YesNo? value = YesNo.FileNotFound;
        switch (value)
        {
            case YesNo.Yes:
                Console.WriteLine("Yes");
                break;
            case YesNo.No:
                Console.WriteLine("No");
                break;
            default:
                Console.WriteLine("default");
                break;
        }
    }
}

여전히 인쇄 default됩니다.


null 통합 연산자 ??사용하여 null스위치 값을 다음 이외의 특정 케이스 레이블 로 라우팅 할 수 있습니다 default.

public static IEnumerable<String> AsStrings(this IEnumerable<Char[]> src)
{
    Char[] rgch;

    var e = src.GetEnumerator();
    while (e.MoveNext())
    {
        switch ((rgch = e.Current)?.Length ?? -1)
        {
            case -1:    // <-- value when e.Current is 'null'
                yield return null;
                break;
            case 0:
                yield return String.Empty;
                break;
            case 1:
                yield return String.Intern(new String(rgch[0], 1));
                break;
            default:   // 2...n
                yield return new String(rgch);
                break;
        }
    }
}

참조 URL : https://stackoverflow.com/questions/14950532/how-will-ac-sharp-switch-statements-default-label-handle-a-nullable-enum

반응형