C#自动结构的深层副本 [英] C# Automatic deep copy of struct

查看:143
本文介绍了C#自动结构的深层副本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个结构, MYSTRUCT ,具有私有成员私人布尔[] boolArray; 和方法 ChangeBoolValue(INT指数,布尔值)

I have a struct, MyStruct, that has a private member private bool[] boolArray; and a method ChangeBoolValue(int index, bool Value).

我有一个类, MyClass的,有一个字段公共MYSTRUCT的bool {得到;私人集; }

I have a class, MyClass, that has a field public MyStruct bools { get; private set; }

当我创建从现有新MYSTRUCT对象,然后应用方法ChangeBoolValue(),在这两个对象的布尔数组改变,因为引用的,而不是被称为,被复制到新对象。例如:

When I create a new MyStruct object from an existing one, and then apply method ChangeBoolValue(), the bool array in both objects is changed, because the reference, not what was referred to, was copied to the new object. E.g:

MyStruct A = new MyStruct();
MyStruct B = A;  //Copy of A made
B.ChangeBoolValue(0,true);
//Now A.BoolArr[0] == B.BoolArr[0] == true

有没有强迫副本来实现更深层次的复制方式,还是有实现这个不会有同样的问题的方法吗?

Is there a way of forcing a copy to implement a deeper copy, or is there a way to implement this that will not have the same issue?

我有专门做MYSTRUCT一个结构,因为它是值类型,而我不想引用传播。

I had specifically made MyStruct a struct because it was value type, and I did not want references propagating.

推荐答案

运行时执行快速记忆结构的副本而据我所知,这是不可能引进或强迫自己的复制过程他们。你可以介绍你自己的克隆方法甚至一个拷贝构造函数,但你不能强制他们使用它们。

The runtime performs a fast memory copy of structs and as far as I know, it's not possible to introduce or force your own copying procedure for them. You could introduce your own Clone method or even a copy-constructor, but you could not enforce that they use them.

您最好的选择,如果可能的话,使你的结构不变(或不可变类),或在一般的重新设计,以避免此问题。如果您是API的唯一消费者,那么也许你可以保持格外警惕。

Your best bet, if possible, to make your struct immutable (or an immutable class) or redesign in general to avoid this issue. If you are the sole consumer of the API, then perhaps you can just remain extra vigilant.

乔恩斯基特(​​和其他人)所描述的这个问题,虽然会有例外一般来说:可变的结构是邪恶的。
结构可以包含引用引用类型在C#

Jon Skeet (and others) have described this issue and although there can be exceptions, generally speaking: mutable structs are evil. Can structs contain references to reference types in C#

这篇关于C#自动结构的深层副本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆