如何获得泛型类型的副本

本文关键字:副本 泛型类型 何获得 | 更新日期: 2023-09-27 18:17:09

在Hosam Aly对"在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());