【发布时间】: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