1

我在下面缺少什么?当我尝试list.Clone()克隆没有出现在列表中。

https://stackoverflow.com/a/222640/139698

class Program
{
    static void Main(string[] args)
    {
        List<Customer> list = new List<Customer>();
        list.Clone() //There is no Clone method in the list
    }
}

public static class Extensions
{
    public static IList<T> Clone<T>(this IList<T> listToClone) where T : ICloneable
    {
        return listToClone.Select(item => (T)item.Clone()).ToList();
    }
}

public class Customer
{
    public string ContactName { get; set; }
    public string City { get; set; }
}
4

2 回答 2

5

客户必须实施 ICloneable,因为您的通用条件说 T 必须实施 ICloneable。

public class Customer : ICloneable

于 2012-10-12T02:14:46.777 回答
0

您将需要在类上实现ICloneable接口。Customer此外,由于已经为IList<T>where定义了扩展方法T is ICloneable,您可能希望使用以下语法

        IList<Customer> list = new List<Customer>();
        list.Clone(); 

如果不实现,Clone()扩展方法将不可见CustomerICloneable

于 2012-10-12T02:20:37.927 回答