可以看到array參數並不一樣,一 個是泛型,一個是數組,所以需要為這個方法實現兩個版本,當然,我們先實現 的是ICollection接口中的CopyTo方法:
void ICollection.CopyTo(Array array, int arrayIndex)
{
if (array == null)
{
throw new ArgumentNullException("array");
}
if (array.Rank != 1)
{
throw new ArgumentException(
"不支持多維數組拷貝 ");
}
if (array.GetLowerBound(0) != 0)
{ //檢查參數數組是否下限為
throw new ArgumentException("A non-zero lower bound was provided");
}
if ((arrayIndex < 0) || (arrayIndex > array.Length))
{ //檢查參數數組容量
throw new ArgumentOutOfRangeException(
"arrayIndex", "Need non negative number");
}
if ((array.Length - arrayIndex) < this.Count)
{ //檢查參數數組容量
throw new ArgumentException("Array plus the offset is too small");
}
//把參數array強制轉換為KeyValuePair<TKey, TValue>數組類型
KeyValuePair<TKey, TValue>[] pairArray1 =
array as KeyValuePair<TKey, TValue>[];
if (pairArray1 != null)
{ // 如果轉換成功,則拷貝數據
for (int num1 = 0; num1 < this.Count; num1++)
{
pairArray1[num1 + arrayIndex] =
new KeyValuePair<TKey, TValue>(this.keys[num1],
this.values[num1]);
}
}
else
{ //如果轉換不成功,則把參數array強制轉化為 object數組
object[] objArray1 = array as object[];
if (objArray1 == null)
{
throw new ArgumentException("錯誤的數組類型");
}
try
{
for (int num2 = 0; num2 < this.Count; num2++)
{
objArray1[num2 + arrayIndex] =
new KeyValuePair<TKey, TValue> (this.keys[num2],
this.values[num2]);
}
}
catch (ArrayTypeMismatchException)
{
throw new ArgumentException("錯 誤的數組類型");
}
}
}