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
相关推荐
mudtools3 小时前
.NET驾驭Word之力:玩转文本与格式
c#·.net
唐青枫6 小时前
C#.NET 数据库开发提速秘籍:SqlSugar 实战详解
c#·.net
mudtools1 天前
.NET驾驭Word之力:理解Word对象模型核心 (Application, Document, Range)
c#·.net
侃侃_天下1 天前
最终的信号类
开发语言·c++·算法
echoarts1 天前
Rayon Rust中的数据并行库入门教程
开发语言·其他·算法·rust
Aomnitrix1 天前
知识管理新范式——cpolar+Wiki.js打造企业级分布式知识库
开发语言·javascript·分布式
大飞pkz1 天前
【设计模式】C#反射实现抽象工厂模式
设计模式·c#·抽象工厂模式·c#反射·c#反射实现抽象工厂模式
每天回答3个问题1 天前
UE5C++编译遇到MSB3073
开发语言·c++·ue5
伍哥的传说1 天前
Vite Plugin PWA – 零配置构建现代渐进式Web应用
开发语言·前端·javascript·web app·pwa·service worker·workbox
小莞尔1 天前
【51单片机】【protues仿真】 基于51单片机八路抢答器系统
c语言·开发语言·单片机·嵌入式硬件·51单片机