【问题标题】:Pattern Matching in C# 7.0C# 7.0 中的模式匹配
【发布时间】:2017-09-29 07:23:48
【问题描述】:

我在 Microsoft 的博客“C# 7.0 中的新功能”中找到了有关 Switch-Case 模式匹配的代码 sn-p:

switch(shape)
{
    case Circle c:
        WriteLine($"circle with radius {c.Radius}");
        break;
    case Rectangle s when (s.Length == s.Height):
        WriteLine($"{s.Length} x {s.Height} square");
        break;
    case Rectangle r:
        WriteLine($"{r.Length} x {r.Height} rectangle");
        break;
    default:
        WriteLine("<unknown shape>");
        break;
    case null:
        throw new ArgumentNullException(nameof(shape));
}

现在我的问题:

如何将它与 switch-case 或其他结构一起使用? shape 是什么?它应该是 Shape 的一个实例(Circle、Rectangle 等的超类)吗?

我的第二个问题是:如何使用when?是新关键字吗?编译器是通过什么方式验证的?

谢谢。

【问题讨论】:

    标签: switch-statement pattern-matching c#-7.0


    【解决方案1】:

    Here模式匹配的当前文档。

    是的,ShapeCircleRectangle 的超类。

    when 关键字用于向case 块添加额外条件。几乎与异常过滤器一起使用的方式(由 C# 6 引入)。

    【讨论】:

    • 为什么比说在Shape中定义一个抽象方法并在这里调用它更有好处?
    • @Alan,如果你做不到怎么办?
    • 明白了。这是有道理的。
    猜你喜欢
    • 2017-11-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-12-17
    • 1970-01-01
    • 1970-01-01
    • 2020-12-04
    • 1970-01-01
    相关资源
    最近更新 更多