switch两种写法对比

public static int? Test1(string str)
{
    return str switch
    {
        "A" => 1,
        "B" => 2,
        "C" => 3,
        _ => default,
    };
}
public static int? Test2(string str)
{
    switch (str)
    {
        case "A":
            return 1;
        case "B":
            return 2;
        case "C":
            return 3;
        default:
            return default;
    }
}

执行下面的代码

Console.WriteLine("Test1:" + Test1("My IO"));
Console.WriteLine("Test2:" + Test2("My IO"));

 Test1返回了int而不是int?的默认值!

原文地址:https://www.cnblogs.com/dandan00056/p/15241378.html