在C#中可以使用以下运算符和表达式来执行类型检查或类型转换:
如现有变量high,if(high is int){int++;}
比较以上可知,is只是检查给定类型是否可转换为给定类型,as运算符将表达式结果显式转换为给定的引用或可以为 null 的值类型
在运行时,显式转换可能不会成功,强制转换表达式可能会引发异常。这是也是强制转换和as的区别,as 运算符永远不会引发异常。
在这里再说一下模式匹配(pattern matching)
模式匹配可以理解为类型检查的扩展,当测试值匹配某种类型时,将创建一个该类型的变量(这是和以上as和强制转换的区别)
有is类型模式,语法是 E IS T varname,如下代码:
public static double ComputeAreaModernIs(object shape)
{
if (shape is Square s)
return s.Side * s.Side;
else if (shape is Circle c)
return c.Radius * c.Radius * Math.PI;
else if (shape is Rectangle r)
return r.Height * r.Length;
// elided
throw new ArgumentException(
message: "shape is not a recognized shape",
paramName: nameof(shape));
}
switch语句,如下代码:
public static double ComputeArea_Version3(object shape)
{
switch (shape)
{
case Square s when s.Side == 0:
case Circle c when c.Radius == 0:
return 0;
case Square s:
return s.Side * s.Side;
case Circle c:
return c.Radius * c.Radius * Math.PI;
default:
throw new ArgumentException(
message: "shape is not a recognized shape",
paramName: nameof(shape));
}
}
模式匹配扩展了switch语句的使用范围
原文:https://www.cnblogs.com/lumingprince/p/14103682.html