• C# as 和 is 运算符区别和用法
  • 发布于 1个月前
  • 193 热度
    0 评论
前言
在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 = "堆代码 duidaima.com";
            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
用户评论