Does it make sense to define a struct with a reference type member?

前端 未结 4 1452
我寻月下人不归
我寻月下人不归 2020-12-02 23:44

Is there any sense in defining a struct with a reference type member (and not defining it as a class)? For example, to define this struct:

public struct Some         


        
4条回答
  •  误落风尘
    2020-12-03 00:15

    In general, a struct should only contain a public and/or mutable field of a reference type if one of the following conditions applies:

    1. All instances of that type may be regarded as inherently immutable (as is the case of `string`)
    2. The semantics of the struct clearly imply that the field identifies the object to which it refers, rather than encapsulating its state, and that the state of the object referred to by the field is not considered part of the struct. For example, in a KeyValuePair, one would expect the `Value` to identify a form instance; moving the form around the screen would change `Value.Bounds`, but would not be considered to change `Value` (which would continue to refer to the same form, regardless of its on-screen location)

    If neither condition applies, it may be appropriate for a structure to hold a field of a reference type provided all of the following conditions apply:

    1. The field never holds a reference to any mutable object which the struct did not itself create.
    2. The reference must never be exposed, nor ever have been exposed, to any code that might in future mutate the object it refers to.
    3. All mutations that are ever going to be done on the object to which the field is going to refer must be performed before a reference is stored in the field.

    In other words, an object reference which is used to encapsulate the state of an object (as opposed to merely identifying it) should only be stored in a struct field if there is no execution path via which the object to which it refers might be modified.

提交回复
热议问题