Stack<T> implements ICollection, but has methods from ICollection<T>

南笙酒味 提交于 2019-12-08 19:44:19

问题


I'm trying to create a custom collection based on Stack<T>. When I look at Stack<T> [from metadata] in visual studio, it shows that Stack<T> implements ICollection, which would require it to implement ICollection's CopyTo(Array array, index) method, but instead, it is shown as having ICollection<T>'s CopyTo(T[] array, index) method. Can someone explain why this is the case?

I'm trying to create a collection that mimics Stack<T> pretty heavily. When I implement ICollection as stack does, it requires me to use the CopyTo(Array array, index) method, but what I really want is to use the CopyTo(T[] array, index) method, like Stack<T> does. Is there a way to achieve this without implementing ICollection<T>?


回答1:


As others have written, you can use explicit interface implementation to satisfy your non-generic interface:

void ICollection.CopyTo(Array array, int arrayIndex)
{
  var arrayOfT = array as T[];
  if (arrayOfT == null)
    throw new InvalidOperationException();
  CopyTo(arrayOfT, arrayIndex); // calls your good generic method
}



回答2:


I guess the method CopyTo(Array array, index) is implemented explicitly. This means, you will only see that method if you see the object as an ICollection:

var collection = (ICollection)stack;
collection.CopyTo(array, 0);


来源:https://stackoverflow.com/questions/10589803/stackt-implements-icollection-but-has-methods-from-icollectiont

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!