Do interface variables have value-type or reference-type semantics?

后端 未结 4 630
醉酒成梦
醉酒成梦 2021-02-02 17:13

Do interface variables have value-type or reference-type semantics?

Interfaces are implemented by types, and those types are either value types or reference types. Obvi

4条回答
  •  -上瘾入骨i
    2021-02-02 17:35

    Variables of interface type will have always have either immutable semantics, mutable reference semantics, or "oddball" semantics (something other than normal reference or value semantics). If variable1 and variable2 are both declared as the same interface type, one performs variable2 = variable1, and one never again writes to either variable, the instance referred to by variable1 will always be indistinguishable from the one referred to be variable2 (since it will be the same instance).

    Generic types with interface constraints may have immutable semantics, mutable reference semantics, or "quirky" semantics, but may also have mutable value semantics. This can be dangerous if the interface is not documented as having mutable value semantics. Unfortunately, there is no way to constrain an interface to have either immutable semantics or mutable value semantics (meaning that following variable2 = variable1, it should not be possible to change variable1 by writing variable2, nor vice versa). One could add a "struct" constraint along with the interface constraint, but that would exclude classes which have immutable semantics while not excluding structs that have reference semantics.

提交回复
热议问题