在Hosam Aly's answer对于“在 C# 中设置/扩展列表长度”这个问题,建议使用以下代码:
public static List<T> EnsureSize<T>(this List<T> list, int size, T value)
{
if (list == null) throw new ArgumentNullException("list");
if (size < 0) throw new ArgumentOutOfRangeException("size");
int count = list.Count;
if (count < size)
{
int capacity = list.Capacity;
if (capacity < size)
list.Capacity = Math.Max(size, capacity * 2);
while (count < size)
{
list.Add(value);
++count;
}
}
return list;
}
通过引用将值添加到列表中。 如何通过使用副本来确保列表的大小?
(我尝试使用 Clone() 和 ICloneable 但没有成功,因为某些类型,例如 List<T> 返回一个浅拷贝,而我想要一个深拷贝。)
请您参考如下方法:
只要您对 T 一无所知,无论它是可克隆的还是可序列化的或一百万种其他复制它的方法,您都将不得不依赖调用者提供此类方法。你想要任意数量的新 T,最简单的版本是在你的方法签名中请求一个生成器:
public static List<T> EnsureSize<T>(this List<T> list, int size, Func<T> generator)
{
if (list == null) throw new ArgumentNullException("list");
if (size < 0) throw new ArgumentOutOfRangeException("size");
int count = list.Count;
if (count < size)
{
int capacity = list.Capacity;
if (capacity < size)
list.Capacity = Math.Max(size, capacity * 2);
while (count < size)
{
list.Add(generator());
++count;
}
}
return list;
}
调用它看起来像这样:
myList.EnsureSize(42, () => new Item());
或者这个:
myList.EnsureSize(42, () => existingItem.Clone());
或者可能是这样:
myList.EnsureSize(42, () => StaticItemFactory.CreateNew());
或任何其他构造新 T 的方法。
