代码改变世界

关于 C# 8.0 的 Switch Case When 的用法

2019-06-30 15:16  音乐让我说  阅读(10971)  评论(0)    收藏  举报

直接贴代码了:

static void Main(string[] args)
{
    SwitchSample();
}

private static void SwitchSample()
{
    Switch(new Circle { Radius = 10 });
    Switch(new Rectangle { Height = 10, Width = 10 });
    Switch(new Rectangle { Height = 20, Width = 30 });
}

private static void Switch(object o)
{
    switch (o)
    {
        case Circle c:
            Console.WriteLine($"it's a circle with radius {c.Radius}");
            break;
        case Rectangle r when (r.Width == r.Height):
            Console.WriteLine($"it's a square with width {r.Width}");
            break;
        case Rectangle r:
            Console.WriteLine($"it's a rectangle with width {r.Width} and height {r.Height}");
            break;
        default:
            break;
    }
}

 

运行截图:

谢谢浏览!