我在微软的博客'C#7.0中的新功能'中找到了关于Switch-Case模式匹配的代码片段:
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));
}
现在我的问题:
如何将其与开关盒或其他结构一起使用?什么是shape
?它应该是Shape的实例(Circle,Rectangle等的超类)吗?
我的第二个问题就是:我如何使用when
?这是一个新关键字吗?编译器以哪种方式验证它?
感谢。
答案 0 :(得分:3)