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


直接贴代码了:

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;
    }
}

 

运行截图:

谢谢浏览!


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM