我一直在研究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 代码中?
最佳答案
是的,Array.ConstrainedCopy
与您的示例实现不同。 Array.ConstrainedCopy 事先检查副本是否有可能引发异常,如果有,则根本拒绝复制。例如,从 int[]
复制到 object[]
涉及对 int
进行装箱,这可能会引发 OutOfMemoryException
,因此 Array.ConstrainedCopy 甚至不会尝试复制。
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.
关于c# - Array.ConstrainedCopy() 不仅仅是备份和复制操作吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12002071/