你不能这样做,因为你不能定义List<T>
自己。如果您可以声明自己的List<T>
,那么您将只能这样做,因为您限制的方式为ICloneable<T>
。由于List<T>
确实不会实现ICloneable<T>
,因此您将不得不将T的类型替换为InstanceList,您可以使用执行的控制。
这里是你将如何实现它:
public class InstanceList : List<Instance>, ICloneable<InstanceList>
{
public InstanceList Clone()
{
// Implement cloning guts here.
}
object ICloneable.Clone()
{
return ((ICloneable<InstanceList>) this).Clone();
}
}
public class Instance
{
}
public interface ICloneable<T> : ICloneable where T : ICloneable<T>
{
new T Clone();
}
当然,还有另外一种选择,你可以做。你可以扩大你的泛型一点点,创建一个CloneableList<T>
类型:
public class CloneableList<T> : List<T>, ICloneable<CloneableList<T>>
{
public CloneableList<T> Clone()
{
throw new InvalidOperationException();
}
object ICloneable.Clone()
{
return ((ICloneable<CloneableList<T>>) this).Clone();
}
}
public interface ICloneable<T> : ICloneable where T : ICloneable<T>
{
new T Clone();
}
如果你真的想获得幻想,创造一些限制吨至ICloneable。然后,您可以在Instance类上实现ICloneable,并且可以在ICloneable<T>
列表中包含任何其他内容,从而以完全相同的方式处理每个CloneableList<T>
,从而为您要创建的每个可复制列表避免不同的ICloneable<T>
实现。
public class CloneableList<T> : List<T>, ICloneable<CloneableList<T>> where T : ICloneable
{
public CloneableList<T> Clone()
{
var result = new CloneableList<T>();
result.AddRange(this.Select(item => (T) item.Clone()));
return result;
}
object ICloneable.Clone()
{
return ((ICloneable<CloneableList<T>>) this).Clone();
}
}
public interface ICloneable<T> : ICloneable where T : ICloneable<T>
{
new T Clone();
}
这工作。一个变化:T克隆();需要新的关键字来覆盖object.Clone()。我现在看到我的想法是不正确的。我克隆的类别不是列表。谢谢! –
sapbucket
请务必查看我所做的修改。第二个和第三个选项比我列出的第一个选项灵活得多。 –
为什么它需要第二个对象ICloneable.Clone()方法?我认为这个接口只需要一个Clone()操作的方法。 – sapbucket