如何实现ICollection.CopyTo方法?

rel*_*dom 14 .net c#

我正在编写一个实现ICollection<T>ICollection接口的类.

MSDN说这些有点不同.ICollection<T>.CopyTo采取T[]论证,而ICollection.CopyTo采取System.Array争论.抛出的异常之间也存在差异.

这是我对泛型方法的实现(我相信它的功能完全正常):

void ICollection<PlcParameter>.CopyTo(PlcParameter[] array, int arrayIndex)
{
    if (array == null)
        throw new ArgumentNullException("array");
    if (arrayIndex < 0)
        throw new ArgumentOutOfRangeException("arrayIndex");
    if (array.Length - arrayIndex < Count)
        throw new ArgumentException("Not enough elements after arrayIndex in the destination array.");

    for (int i = 0; i < Count; ++i)
        array[i + arrayIndex] = this[i];
}
Run Code Online (Sandbox Code Playgroud)

但是,该方法的非泛型版本让我感到困惑.首先,如何检查以下异常情况

源ICollection的类型不能自动转换为目标数组的类型.

第二,有没有办法利用现有的通用实现来减少代码重复?

这是我的在制品实施:

void ICollection.CopyTo(Array array, int index)
{
    if (array == null)
        throw new ArgumentNullException("array");
    if (index < 0)
        throw new ArgumentOutOfRangeException("arrayIndex");
    if (array.Rank > 1)
        throw new ArgumentException("array is multidimensional.");
    if (array.Length - index < Count)
        throw new ArgumentException("Not enough elements after index in the destination array.");

    for (int i = 0; i < Count; ++i)
        array.SetValue(this[i], i + index);
}
Run Code Online (Sandbox Code Playgroud)

Jon*_*nna 5

您已经完成了实现ICollection<T>.CopyTo.

有四种可能ICollection.CopyTo

  1. 它将与ICollection<T>.
  2. 它会因为失败的原因ICollection<T>而失败。
  3. 由于等级不匹配,它将失败。
  4. 由于类型不匹配,它将失败。

我们可以通过调用进入来处理前两个ICollection<T>.CopyTo

在每一种情况下array as PlcParameter[]都会给我们一个对数组的引用,强类型。

在后一种情况下,它不会。

我们确实想array == null单独捕获:

void ICollection.CopyTo(Array array, int index)
{
  if (array == null)
    throw new ArgumentNullException("array");
  PlcParameter[] ppArray = array as PlcParameter[];
  if (ppArray == null)
    throw new ArgumentException();
  ((ICollection<PlcParameter>)this).CopyTo(ppArray, index);
}
Run Code Online (Sandbox Code Playgroud)

如果你真的想要你可以array.Rank == 1ppArray为空的情况下进行测试,并相应地更改错误消息。

(顺便说一句,你为什么要明确实施ICollection<PlcParameter>.CopyTo?明确实施工作可能就足够有用了,所以人们不必全部投入。)