c# - If 语句 With 是关键字并与 Null 进行比较

标签 c# .net null typechecking

我今天在我的 PC 上安装了 Reshaper 来检查它,每当我的代码中有以下语句时,我都会从 Resharper 获得一条信息,即不需要与 Null 进行比较。为什么?

声明如下:

if (dataGrid.ItemsSource != null && dataGrid.ItemsSource is DataGridCollectionView)

我正在检查类型是否是我想要的类型以及值是否不是 Null

我要求这个是有意义的,因为类型可能是真的,尽管值可能仍然是 Null。我想我一定在文档中遗漏了一些关于此的内容。

为什么 Reshaper 说我不需要与 null 进行比较?

我错过了什么?

最佳答案

如果对象为 null,is 运算符将始终返回 false,因此您无需在测试类型之前检查是否为 null。

来自documentation :

An is expression evaluates to true if the provided expression is non-null, and the provided object can be cast to the provided type without causing an exception to be thrown.

关于c# - If 语句 With 是关键字并与 Null 进行比较,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19766001/

相关文章:

c# - 为什么我的 .NET Standard 2.0(多目标)项目对依赖程序集之一发出警告?

c# - 使用单行 `null` 将 'if' 值分配给 Nullable<DateTime>

javascript - 来自其他站点的链接应打开该站点的第一个链接

c# - .Net 中的模拟在读取注册表项时崩溃(LinkLabel SecurityException)

c# - 找不到包 'Microsoft.AspNet.WebApi.Client' .Net Core 2.2 的编译库位置

C# - 程序员面试挑战 - 接口(interface)和模式编程

MYSQL LIKE 通配符排除 NULL 值

java - 按字典顺序比较两个可能为 null 的 Java 字符串

c# - 正确区分bool?和 bool 在 C#

c# - 检查当前是否没有用户登录到 Windows