推荐答案
// www.javascriptcn.com code example
// 示例代码:C# 中的模式匹配
public string GetShapeDescription(object shape)
{
switch (shape)
{
case Circle c:
return $"Circle with radius {c.Radius}";
case Rectangle r when r.Width == r.Height:
return $"Square with side {r.Width}";
case Rectangle r:
return $"Rectangle with width {r.Width} and height {r.Height}";
case null:
return "Shape is null";
default:
return "Unknown shape";
}
}本题详细解读
模式匹配的基本概念
模式匹配是 C# 7.0 引入的一项功能,允许你在 switch 语句或 is 表达式中根据对象的类型或属性进行条件分支。它简化了类型检查和类型转换的代码,使代码更加简洁和易读。
switch 语句中的模式匹配
在 switch 语句中,你可以使用模式匹配来检查对象的类型,并根据类型执行相应的代码块。例如:
case Circle c:
return $"Circle with radius {c.Radius}";在这个例子中,Circle c 是一个类型模式,它检查 shape 是否是 Circle 类型,如果是,则将 shape 转换为 Circle 类型的变量 c,并执行相应的代码块。
when 子句
when 子句允许你在模式匹配中添加额外的条件。例如:
case Rectangle r when r.Width == r.Height:
return $"Square with side {r.Width}";在这个例子中,when r.Width == r.Height 是一个额外的条件,只有当 Rectangle 的宽度和高度相等时,才会执行这个代码块。
null 检查
模式匹配还可以用于检查对象是否为 null。例如:
case null:
return "Shape is null";默认情况
如果没有任何模式匹配成功,可以使用 default 分支来处理未知的情况。例如:
default:
return "Unknown shape";总结
模式匹配是 C# 中非常强大的功能,它使得类型检查和条件分支更加简洁和直观。通过使用模式匹配,你可以减少代码中的冗余,并提高代码的可读性和可维护性。