将条件表达式用于赋值(IDE0045)
财产 | 价值 |
---|---|
规则 ID | IDE0045 |
标题 | 将条件表达式用于赋值 |
类别 | 样式 |
子类别 | 语言规则(表达式级首选项) |
适用的语言 | C# 和 Visual Basic |
引入的版本 | Visual Studio 2017 |
选项 | dotnet_style_prefer_conditional_expression_over_assignment |
概述
此样式规则涉及在需要条件逻辑的赋值中使用 三元条件表达式 与 if-else 语句。
选项
选项指定希望规则强制实施的行为。 有关配置选项的信息,请参阅 选项格式。
dotnet_style_更喜欢条件表达式而不是赋值
财产 | 价值 | 描述 |
---|---|---|
选项名称 | 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
有关详细信息,请参阅 如何取消代码分析警告。