gpt4 book ai didi

c# - Array.ConstrainedCopy() 是否不仅仅是备份和复制操作?

转载 作者:行者123 更新时间:2023-11-30 22:26:13 29 4
gpt4 key购买 nike

我一直在查看 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/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com