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
相关推荐
小码编匠12 小时前
WPF 中的高级交互通过右键拖动实现图像灵活缩放
后端·c#·.net
唐青枫19 小时前
C#.NET 定时任务与队列利器:Hangfire 完整教程
c#·.net
hez20101 天前
Runtime Async - 步入高性能异步时代
c#·.net·.net core·clr
mudtools2 天前
.NET驾驭Word之力:玩转文本与格式
c#·.net
唐青枫2 天前
C#.NET 数据库开发提速秘籍:SqlSugar 实战详解
c#·.net
mudtools2 天前
.NET驾驭Word之力:理解Word对象模型核心 (Application, Document, Range)
c#·.net
侃侃_天下3 天前
最终的信号类
开发语言·c++·算法
echoarts3 天前
Rayon Rust中的数据并行库入门教程
开发语言·其他·算法·rust
Aomnitrix3 天前
知识管理新范式——cpolar+Wiki.js打造企业级分布式知识库
开发语言·javascript·分布式
大飞pkz3 天前
【设计模式】C#反射实现抽象工厂模式
设计模式·c#·抽象工厂模式·c#反射·c#反射实现抽象工厂模式