前言
在C#中,as 和 is 關鍵字都用于處理類型轉換的運算符,但它們有不同的用途和行為。本文我們將詳細解釋這兩個運算符的區別和用法。
is 運算符
is 運算符用于檢查對象是否是某個特定類型,或者是否可以轉換為該類型。它返回一個布爾值 (true 或 false)。
string title = "Hello DotNetGuide";
if (title is string)
{
Console.WriteLine("是 string 類型");
}
else
{
Console.WriteLine("不是 string 類型");
}
if (title is not null)
{
Console.WriteLine("不為 null");
}
else
{
Console.WriteLine("為 null");
}
模式匹配
C# 7.0 引入了模式匹配,允許在 is 表達式中進行類型檢查和轉換:
object obj = "追逐時光者";
if (obj is string str)
{
Console.WriteLine($" {str}");
}
else
{
Console.WriteLine("不是指定類型");
}
列表模式
從 C# 11 開始,可以使用列表模式來匹配列表或數組的元素。以下代碼檢查數組中處于預期位置的整數值:
int[] empty = [];
int[] one = [1];
int[] odd = [1, 3, 5];
int[] even = [2, 4, 6];
int[] fib = [1, 1, 2, 3, 5];
Console.WriteLine(odd is [1, _, 2, ..]); // false
Console.WriteLine(fib is [1, _, 2, ..]); // true
Console.WriteLine(fib is [_, 1, 2, 3, ..]); // true
Console.WriteLine(fib is [.., 1, 2, 3, _ ]); // true
Console.WriteLine(even is [2, _, 6]); // true
Console.WriteLine(even is [2, .., 6]); // true
Console.WriteLine(odd is [.., 3, 5]); // true
Console.WriteLine(even is [.., 3, 5]); // false
Console.WriteLine(fib is [.., 3, 5]); // true
as 運算符
as 運算符嘗試將對象轉換為特定類型,如果轉換失敗,則返回 null 而不是拋出異常。它通常用于在不需要顯式檢查對象是否為特定類型的情況下進行安全的類型轉換。
注意:as 運算符僅考慮引用、可以為 null、裝箱和取消裝箱轉換。它不支持用戶定義的或復雜的類型轉換,這種情況需要使用強制轉換表達式。
object title = "Hello DotNetGuide";
string str = title as string;
if (str != null)
{
Console.WriteLine("是 string 類型: " + str);
}
else
{
Console.WriteLine("不是 string 類型");
}
int? num = title as int?;
if (num.HasValue)
{
Console.WriteLine("是 int 類型: " + num.Value);
}
else
{
Console.WriteLine("不是 int 類型");
}
參考文章
- https://learn.microsoft.com/zh-cn/dotnet/csharp/language-reference/operators/is
- https://learn.microsoft.com/zh-cn/dotnet/csharp/language-reference/operators/type-testing-and-cast#as-operator
該文章在 2025/1/24 10:32:00 編輯過