C# Automatic deep copy of struct

前端 未结 6 1944
没有蜡笔的小新
没有蜡笔的小新 2021-01-17 10:53

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

6条回答
  •  傲寒
    傲寒 (楼主)
    2021-01-17 11:34

    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.

    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.

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

提交回复
热议问题