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

标签 c# .net arrays

我一直在研究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/

相关文章:

c# - WPF 窗口可以包含一个 child 吗?

c# - 使用不同的根元素名称反序列化

.net - 在 C# 中实现编译器最有趣和最有前途的方法是什么?

php - 如何从 MySQL 数据库获取数据到以一个字段作为数组索引的数组

javascript - 相同数组不同结果

c# - 从 Node.js 中的 C# 工具反序列化 byte[]

c# - 取消 Item_Open 导致崩溃

c# - 从 linq 中的类返回可枚举值?

c# - 检查数据表中是否有空值的最佳方法

python - 数组比较与numpy中的元素比较不匹配