好的,我的实际问题是这样的:我正在实现一个 IList<T>
。当我到达 CopyTo(Array array, int index)
时,这是我的解决方案:
void ICollection.CopyTo(Array array, int index)
{
// Bounds checking, etc here.
if (!(array.GetValue(0) is T))
throw new ArgumentException("Cannot cast to this type of Array.");
// Handle copying here.
}
这在我的原始代码中有效,现在仍然有效。但它有一个小缺陷,在我开始为它构建测试时才暴露出来,特别是这个:
public void CopyToObjectArray()
{
ICollection coll = (ICollection)_list;
string[] testArray = new string[6];
coll.CopyTo(testArray, 2);
}
现在,这个测试应该通过了。它抛出了ArgumentException
,说明无法转换。为什么呢?因为 array[0] == null
。当检查一个被设置为null
的变量时,is
关键字总是返回false。现在,这对于各种原因都非常方便,包括避免空指针引用等。我最终想到的类型检查方法是:
try
{
T test = (T)array.GetValue(0);
}
catch (InvalidCastException ex)
{
throw new ArgumentException("Cannot cast to this type of Array.", ex);
}
这并不是很优雅,但它可以运行... 不过有更好的方法吗?