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
相关推荐
Ivanqhz3 分钟前
MLIR OpBuilder
开发语言·python·mlir
zxy28472253011 小时前
C# 音频倍速播放
c#·音频·naudio·soundtouch·倍速
红宝村村长1 小时前
windows笔记本双系统ubuntu设置
开发语言
菜鸟~noob2333 小时前
【电子战】第15篇:混合定位——TDOA/FDOA/AOA 联合【含matlab代码】
开发语言·matlab
Dreams_l4 小时前
死信队列和延迟队列介绍
java·开发语言
Water_Sunzhipeng4 小时前
HandyControl Demo 设置特定框架记录
c#
Zenova EdgeOS4 小时前
Python 工业边缘 redis-py 异步实战
开发语言·redis·python
czhc11400756635 小时前
插补、另存为、标记过滤、采集超时——今天聊的四件事
c#
君顾15 小时前
西安 24 小时自助健身房系统开发实战指南
java·开发语言·健身房
小羊没烦恼!6 小时前
Memory 记忆设计讨论:Agent Memory 的数据模型可以怎么设计
java·开发语言·前端·c++·c#