财产 | 价值 |
---|---|
规则 ID | IDE0301 |
标题 | 使用 empty 的集合表达式 |
类别 | 样式 |
子类别 | 语言规则(表达式级首选项) |
适用的语言 | C# 12+ |
选项 | dotnet_style_prefer_collection_expression |
概述
此规则查找类似于 Array.Empty<T>()
(返回空集合的方法调用)或 ImmutableArray<T>.Empty
(返回空集合的属性)的代码,并提供将其替换为 集合表达式([]
)。
选项
选项指定希望规则强制实施的行为。 有关配置选项的信息,请参阅 选项格式。
dotnet_style_prefer_collection_expression
财产 | 价值 | 描述 |
---|---|---|
选项名称 | dotnet_style_prefer_collection_expression | |
选项值 | true | when_types_exactly_match |
仅当类型完全匹配时,首选使用集合表达式,例如,List<int> list = new List<int>() { 1, 2 }; 。 |
when_types_loosely_match * |
优先使用集合表达式,即便类型不完全匹配,例如 IEnumerable<int> list = new List<int>() { 1, 2 }; 。 目标类型必须与右侧的类型匹配或以下类型之一:IEnumerable<T>、ICollection<T>、IList<T>、IReadOnlyCollection<T>、IReadOnlyList<T>。 |
|
false | never |
禁用规则。 | |
默认选项值 | when_types_loosely_match * |
*使用此选项时,代码修复可能会更改代码的语义。
例
// Code with violations.
int[] i = Array.Empty<int>();
IEnumerable<int> j = Array.Empty<int>();
ReadOnlySpan<int> span = ReadOnlySpan<int>.Empty;
// Fixed code.
int[] i = [];
IEnumerable<int> j = [];
ReadOnlySpan<int> span = [];
以下代码片段显示了具有自定义类型的示例。
public class Program
{
public static void Main()
{
// IDE0301 violation.
MyList<int> x = MyList<int>.Empty;
// IDE0301 fixed code.
MyList<int> x = [];
}
}
class MyList<T> : IEnumerable<T>
{
public static MyList<T> Empty { get; }
public IEnumerator<T> GetEnumerator() => default;
IEnumerator IEnumerable.GetEnumerator() => default;
}
禁止显示警告
如果只想取消单个冲突,请将预处理器指令添加到源文件以禁用,然后重新启用规则。
#pragma warning disable IDE0301
// The code that's violating the rule is on this line.
#pragma warning restore IDE0301
若要禁用文件、文件夹或项目的规则,请将其严重性设置为 none
中的 。
[*.{cs,vb}]
dotnet_diagnostic.IDE0301.severity = none
若要禁用所有代码样式规则,请将类别 Style
的严重性设置为 none
中的 。
[*.{cs,vb}]
dotnet_analyzer_diagnostic.category-Style.severity = none
有关详细信息,请参阅 如何取消代码分析警告。
另请参阅
- 对数组(IDE0300) 使用集合表达式