C# 关键字 as is

as

  • as 运算符将表达式结果显式转换为给定的引用或可以为 null 值的类型。

  • 如果无法进行转换,则 as 运算符返回 null。

  • 与强制转换表达式 不同,as 运算符永远不会引发异常。

csharp 复制代码
int[] numbers ={10, 20, 30};
IList<int> indexable = numbers as IList<int>;
if (indexable != null)
{
    Console.WriteLine(indexable[0] + indexable[indexable.Count - 1]);  // output: 40
}

is

is 运算符检查表达式的结果是否与给定的类型相匹配

检查是否为 null,如下例所示:

csharp 复制代码
if (input is null)
{
    return;
}

可使用否定模式 执行非 null 检查

csharp 复制代码
if (result is not null)
{
    Console.WriteLine(result.ToString());
}

从 C# 11 开始,可以使用列表模式来匹配列表或数组的元素。 以下代码检查数组中处于预期位置的整数值:

csharp 复制代码
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
相关推荐
闲人编程1 天前
Python游戏开发入门:Pygame实战
开发语言·python·游戏·pygame·毕设·codecapsule
是苏浙1 天前
零基础入门C语言之枚举和联合体
c语言·开发语言
报错小能手1 天前
C++笔记(面向对象)静态联编和动态联编
开发语言·c++·算法
小肖爱笑不爱笑1 天前
2025/11/5 IO流(字节流、字符流、字节缓冲流、字符缓冲流) 计算机存储规则(ASCII、GBK、Unicode)
java·开发语言·算法
手握风云-1 天前
Java 数据结构第二十八期:反射、枚举以及 lambda 表达式
java·开发语言
ᐇ9591 天前
Java Vector集合全面解析:线程安全的动态数组
java·开发语言
我是唐青枫1 天前
C#.NET Random 深入解析:随机数生成原理与最佳实践
c#·.net
光头闪亮亮1 天前
电子发票解析工具-c#桌面应用开发案例详解
c#
Hello_WOAIAI1 天前
2.4 python装饰器在 Web 框架和测试中的实战应用
开发语言·前端·python
搬山.摧城1 天前
线程池和单例模式
开发语言·单例模式