代码检查:冗余的容量实参
此检查会报告值小于已为 capacity 提供元素数目的 List<T> 实参。 在这种情况下,在计算初始值设定项或集合表达式时,列表将需要增长,因此指定的初始容量没有意义。
检查适用于 new List<T>(capacity) { ... } 初始值设定项及使用 with(capacity: ...) 的 C# 集合表达式。
示例
using System.Collections.Generic;
var numbers = new List<int>(capacity: 2) { 1, 2, 3 };
using System.Collections.Generic;
var numbers = new List<int>(capacity: 3) { 1, 2, 3 };
集合表达式示例
using System.Collections.Generic;
List<int> numbers = [with(capacity: 2), 1, 2, 3];
using System.Collections.Generic;
List<int> numbers = [with(capacity: 3), 1, 2, 3];
快速修复
将容量更新为提供元素的数量。 对于集合表达式,如果不需要显式容量,快速修复还可以移除 with(...) 元素。
2026年 7月 17日