使用条件表达式进行赋值 (IDE0045)

属性
规则 ID IDE0045
标题 使用条件表达式进行赋值
类别 Style
Subcategory 语言规则(表达式级首选项)
适用的语言 C# 和 Visual Basic
引入的版本 Visual Studio 2017
选项 dotnet_style_prefer_conditional_expression_over_assignment

概述

此样式规则涉及对需要条件逻辑的赋值使用三元条件表达式,而不是使用 if-else 语句

选项

选项指定你希望规则强制实施的行为。 若要了解如何配置选项,请参阅选项格式

dotnet_style_prefer_conditional_expression_over_assignment

属性 说明
选项名称 dotnet_style_prefer_conditional_expression_over_assignment
选项值 true 首选使用三元条件进行赋值
false 首选使用 if-else 语句进行赋值
默认选项值 true
// dotnet_style_prefer_conditional_expression_over_assignment = true
string s = expr ? "hello" : "world";

// dotnet_style_prefer_conditional_expression_over_assignment = false
string s;
if (expr)
{
    s = "hello";
}
else
{
    s = "world";
}
' dotnet_style_prefer_conditional_expression_over_assignment = true
Dim s As String = If(expr, "hello", "world")

' dotnet_style_prefer_conditional_expression_over_assignment = false
Dim s As String
If expr Then
    s = "hello"
Else
    s = "world"
End If

抑制警告

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

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

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

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

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

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

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

另请参阅