资产 | 价值 |
---|---|
规则 ID | IDE0306 |
标题 | 将集合表达式用于新的对象 |
类别 | 风格 |
子类别 | 语言规则(表达式级首选项) |
适用的语言 | C# 12+ |
选项 | dotnet_style_prefer_collection_expression |
概述
此规则标志用于放置具有分布元素 () 的..
可用于初始化列表而不是new
列表。 例如,此规则提供简化代码(如
选项
选项指定你希望规则强制实施的行为。 若要了解如何配置选项,请参阅选项格式。
dotnet_style_prefer_collection_expression
资产 | 价值 | DESCRIPTION |
---|---|---|
选项名称 | 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 violation.
List<int> l1 = new List<int>(Enumerable.Range(1, 10));
List<int> m1 = new List<int>(new[] { 1, 2, 3 });
// Fixed code.
List<int> l1 = [.. Enumerable.Range(1, 10)];
List<int> m1 = [.. new[] { 1, 2, 3 }];
抑制警告
如果只想取消单个冲突,请将预处理器指令添加到源文件以禁用,然后重新启用规则。
#pragma warning disable IDE0306
// The code that's violating the rule is on this line.
#pragma warning restore IDE0306
若要禁用文件、文件夹或项目的规则,请在none
中将其严重性设置为。
[*.{cs,vb}]
dotnet_diagnostic.IDE0306.severity = none
若要禁用所有代码样式规则,请在Style
中将类别none
的严重性设置为。
[*.{cs,vb}]
dotnet_analyzer_diagnostic.category-Style.severity = none
有关详细信息,请参阅如何禁止显示代码分析警告。