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
相关推荐
ModestCoder_1 天前
ROS Bag与导航数据集技术指南
开发语言·人工智能·自然语言处理·机器人·具身智能
卡提西亚1 天前
C++笔记-34-map/multimap容器
开发语言·c++·笔记
2***B4491 天前
C++在金融中的QuantLibXL
开发语言·c++·金融
A***07171 天前
C++在游戏中的阴影渲染
开发语言·c++·游戏
2401_837088501 天前
Redisson的multilock原理
java·开发语言
合作小小程序员小小店1 天前
桌面开发,在线%超市销售管理%系统,基于vs2022,c#,winform,sql server数据
开发语言·数据库·microsoft·c#
Q***l6871 天前
C++在计算机图形学中的渲染
开发语言·c++
0和1的舞者1 天前
《网络编程核心概念与 UDP Socket 组件深度解析》
java·开发语言·网络·计算机网络·udp·socket
惜棠1 天前
visual code + rust入门指南
开发语言·后端·rust