好吧,我的实际问题是这样的:我实施了IList<T>
。当我到CopyTo(Array array, int index)
,这是我的解决方案:在C#中正确的可空类型检查?
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);
}
这不完全是优雅,但它的工作原理.. 。还有更好的方法吗?
使用反射肯定会比无效投射更昂贵。 – 2008-10-04 02:19:20
+1努力,以及一个有效的解决方案。虽然表现明智,但我认为我必须与ffpf站在一边,Reflection可能需要漫长的路线。 – 2008-10-04 02:24:10
想想这件事情(还有心理打击),我认为这可能是正确做到这一点的唯一方法。 – 2008-10-04 02:32:01