C#类型检查和强制转换以及模式匹配

在C#中可以使用以下运算符和表达式来执行类型检查或类型转换:

  • is 运算符:检查表达式的运行时类型是否与给定类型兼容,语法是:E is T

如现有变量high,if(high is int){high++;}

  • as 运算符:用于将表达式显式转换为给定类型(如果其运行时类型与该类型兼容)语法是:E as T(等效于:E is T ? (T)(E) : (T)null

比较以上可知,is只是检查给定类型是否可转换为给定类型,as运算符将表达式结果显式转换为给定的引用或可以为 null 的值类型

  • 强制转换表达式(cast expression):执行显式转换,语法是:(T)E

在运行时,显式转换可能不会成功,强制转换表达式可能会引发异常。这是也是强制转换和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语句的使用范围

 

posted @ 2020-12-08 17:13  路鸣  阅读(890)  评论(0编辑  收藏  举报