在C#中可以使用以下運算符和表達式來執行類型檢查或類型轉換:
- is 運算符:檢查表達式的運行時類型是否與給定類型兼容,語法是:E is T
如現有變量high,if(high is int){int++;}
- 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語句的使用范圍