Can structs contain fields of reference types

前端 未结 6 2090
一生所求
一生所求 2020-11-30 00:30

Can structs contain fields of reference types? And if they can is this a bad practice?

6条回答
  •  無奈伤痛
    2020-11-30 00:52

    The reason you cannot have mutable structs is because of the behavoir of reference types. Read this article: http://www.yoda.arachsys.com/csharp/parameters.html

    When you have a struct that contains an Object (anything that isn't a primitive like int or double) and you copy an instance of the struct, the Object inside isn't "deep" copied, because it is simply a reference (pointer) to a memory location containing the actual class. So if you copy a mutable struct that contains class instances, the copy will be referencing the same instances as the original (Hence bar's list being changed above).

    If you absolutely have to have the struct be mutable, make any class instances inside readonly, or - this is the bad practice - try to ensure that you never make a copy of the struct.

提交回复
热议问题