2

我一直在研究Array.ConstrainedCopy,但在 CLR 内部,我无法弄清楚为什么它的实现如此隐秘。

ConstrainedCopy除了以下内容之外,还做其他事情吗?

[ReliabilityContract(Consistency.WillNotCorruptState, CER.Success)]
static void ConstrainedCopy(Array src, int iSrc, Array dest, int iDest, int len)
{
    Array backup = Array.CreateInstance(dest.GetType().GetElementType(), len);
    Array.Copy(dest, iDest, backup, 0, len);
    try { Array.Copy(src, iSrc, dest, iDest, len); }
    catch { Array.Copy(backup, 0, dest, iDest, len); throw; }
}

如果是这样,它还有什么作用?
如果不是,那么为什么 CLR 对实现进行如此特殊的处理,而不是在纯 C#/.NET 代码中?

4

1 回答 1

3

Yes, Array.ConstrainedCopy is different from your sample implementation. Array.ConstrainedCopy checks beforehand whether there is any chance the copy might throw an exception, and if so, refuses to copy at all. For example, copying from an int[] to an object[] involves boxing the ints, which might throw an OutOfMemoryException, so Array.ConstrainedCopy doesn't even attempt to copy.

object[] dst = { 1, 2 };
int[] src = { 3, 4 };
Array.ConstrainedCopy(src, 0, dst, 0, 2);

ArrayTypeMismatchException occurred

Array.ConstrainedCopy will only work on array types that are provably compatible, without any form of boxing, unboxing, widening, or casting of each array element. Change the array types (i.e., copy a Derived[] to a Base[]), or use a mitigation strategy in the CER for Array.Copy's less powerful reliability contract, such as cloning the array or throwing away the potentially corrupt destination array.

于 2012-08-17T09:04:32.327 回答