使用条件表达式进行返回操作(IDE0046)

财产 价值
规则 ID IDE0046
标题 为返回值使用条件表达式
类别 样式
子类别 语言规则(表达式级首选项)
适用的语言 C# 和 Visual Basic
引入的版本 Visual Studio 2017
选项 dotnet_style_prefer_conditional_expression_over_return

概述

此样式规则涉及对需要条件逻辑的返回语句使用 三元条件表达式if-else 语句

选项

选项指定希望规则强制实施的行为。 有关配置选项的信息,请参阅 选项格式

dotnet_style_prefer_conditional_expression_over_return

财产 价值 描述
选项名称 dotnet_style_prefer_conditional_expression_over_return
选项值 true return 语句首选使用三元条件
false return 语句首选使用 if-else 语句
默认选项值 true
// dotnet_style_prefer_conditional_expression_over_return = true
return expr ? "hello" : "world"

// dotnet_style_prefer_conditional_expression_over_return = false
if (expr)
{
    return "hello";
}
else
{
    return "world";
}
' dotnet_style_prefer_conditional_expression_over_return = true
Return If(expr, "hello", "world")

' dotnet_style_prefer_conditional_expression_over_return = false
If expr Then
    Return "hello"
Else
    Return "world"
End If

禁止显示警告

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

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

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

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

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

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

有关详细信息,请参阅 如何取消代码分析警告

另请参阅