c# – 如何实现ICollection.CopyTo方法?

我正在写一个实现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];
}

然而,非泛型版本的方法让我有点困惑.首先,我如何检查以下异常情况?

The type of the source ICollection cannot be cast automatically to the type of the destination array.

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

这是我正在进行的实施:

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);
}

解决方法

您已经完成了大部分实现ICollection< T> .CopyTo的工作.

ICollection.CopyTo有四种可能性:

>它将与ICollection< T>相同.
>因为ICollection< T>的原因将失败会失败
>由于排名不一致会失败.
>它将因为类型不匹配而失败.

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

在每个这些情况下,数组中的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);
}

如果您真的想要在ppArray为null的情况下测试array.Rank == 1,并相应地更改错误消息.

(BTW,为什么要显式地实现ICollection< PlcParameter> .CopyTo?很明显,有助于明确地执行工作,所以人们不必投入所有.)

相关文章

项目中经常遇到CSV文件的读写需求,其中的难点主要是CSV文件...
简介 本文的初衷是希望帮助那些有其它平台视觉算法开发经验的...
这篇文章主要简单记录一下C#项目的dll文件管理方法,以便后期...
在C#中的使用JSON序列化及反序列化时,推荐使用Json.NET——...
事件总线是对发布-订阅模式的一种实现,是一种集中式事件处理...
通用翻译API的HTTPS 地址为https://fanyi-api.baidu.com/api...