使用模式匹配来避免 as 后跟 null 检查 (IDE0019)

属性
规则 ID IDE0019
标题 使用模式匹配来避免 as 后跟 null 检查
类别 Style
Subcategory 语言规则(模式匹配首选项)
适用的语言 C#
选项 csharp_style_pattern_matching_over_as_with_null_check

概述

此样式规则涉及使用 C# 模式匹配而不是后跟 null 检查的 as 表达式。 此规则类似“IDE0260”,后者可标记 as 表达式的使用,后跟通过 null 条件运算符读取的成员。

选项

此规则的关联选项指定是首选模式匹配还是具有 null 检查的 as 表达式,以确定某些项是否为特定类型。

若要详细了解如何配置选项,请参阅选项格式

csharp_style_pattern_matching_over_as_with_null_check

此选项还配置了规则“IDE0260”。

属性 说明
选项名称 csharp_style_pattern_matching_over_as_with_null_check
选项值 true 倾向于使用模式匹配来确定内容是否为某个特定类型
false 倾向于使用带 null 检查的 as 表达式,来确定内容是否为某个特定类型
默认选项值 true
// csharp_style_pattern_matching_over_as_with_null_check = true
if (o is string s) {...}

// csharp_style_pattern_matching_over_as_with_null_check = false
var s = o as string;
if (s != null) {...}

抑制警告

如果只想抑制单个冲突,请将预处理器指令添加到源文件以禁用该规则,然后重新启用该规则。

#pragma warning disable IDE0019
// The code that's violating the rule is on this line.
#pragma warning restore IDE0019

若要对文件、文件夹或项目禁用该规则,请在配置文件中将其严重性设置为 none

[*.{cs,vb}]
dotnet_diagnostic.IDE0019.severity = none

若要禁用所有代码样式规则,请在配置文件中将类别 Style 的严重性设置为 none

[*.{cs,vb}]
dotnet_analyzer_diagnostic.category-Style.severity = none

有关详细信息,请参阅如何禁止显示代码分析警告

另请参阅