下午好。我在集合上实现 ICloneable 接口时遇到问题。声明了两个类:
public class CloneableSortedList<TKey, TValue> : SortedList<TKey, TValue> where TValue : ICloneable
{
public SortedList<TKey, TValue> Clone()
{
CloneableSortedList<TKey, TValue> clone = new CloneableSortedList<TKey, TValue>();
foreach (KeyValuePair<TKey, TValue> pair in this)
{
clone.Add(pair.Key, (TValue)pair.Value.Clone());
}
return clone;
}
}
public class CloneableList<T> : List<T> where T : ICloneable
{
public List<T> Clone()
{
CloneableList<T> clone = new CloneableList<T>();
clone.AddRange(this);
return clone;
}
}
但是在声明时CloneableSortedList<double, List<int>> clonelist;,会发生错误:
类型“System.Collections.Generic.List”不能用作泛型类型或方法“CloneableSortedList”中的“TValue”类型参数。没有从“System.Collections.Generic.List”到“System.ICloneable”的隐式引用转换。
你能告诉我如何正确声明班级吗CloneableSortedList?
解释:你这里说的是CloneableList继承了List,其中T应该是ICloneable。但是 CloneableList 没有实现 ICloneable 接口(因为你没有在实现的接口中指定它。他们只说 T 必须是 ICloneable )。
解决方案:在这个类中添加另一个 ICloneable 接口的实现。
PS如果有的话,谷歌“显式和隐式接口实现”。