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

前端 未结 4 1453
我寻月下人不归
我寻月下人不归 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:35

    Nine times out of ten, you should be creating a class rather than a structure in the first place. Structures and classes have very different semantics in C#, compared to what you might find in C++, for example. Most programmers who use a structure should have used a class, making questions like this one quite frankly irrelevant.

    Here are some quick rules about when you should choose a structure over a class:

    1. Never.
      ...Oh, you're still reading? You're persistent. Okay, fine.
    2. When you have an explicit need for value-type semantics, as opposed to reference type semantics.
    3. When you have a very small type (the rule of thumb is a memory footprint less than 16 bytes).
    4. When objects represented by your struct will be short-lived and immutable (won't change).
    5. And occasionally, for interop purposes with native code that uses structures.

    But if you've made an informed decision and are truly confident that you do, in fact, need a structure rather than a class, you need to revisit point number 2 and understand what value type semantics are. Jon Skeet's article here should go a long way towards clarifying the distinction.

    Once you've done that, you should understand why defining a reference type inside of a value type (struct) is not a problem. Reference types are like pointers. The field inside of the structure doesn't store the actual type; rather, it stores a pointer (or a reference) to that type. There's nothing contradictory or wrong about declaring a struct with a field containing a reference type. It will neither "slow the object" nor will it "call GC", the two concerns you express in a comment.

提交回复
热议问题