Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
217 views
in Technique[技术] by (71.8m points)

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

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 SomeStruct
{
    string name;
    Int32  place;
}

I asking because I know that a struct is a value type, and to define in it some reference type does not make any sense.

Am I right? Can someone explain this?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...