用引用类型成员定义结构体有意义吗? [英] Does it make sense to define a struct with a reference type member?

查看:22
本文介绍了用引用类型成员定义结构体有意义吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

定义具有引用类型成员的结构体(而不是将其定义为类)是否有意义?例如,定义这个结构:

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?

推荐答案

十有八九,您应该首先创建一个类而不是一个结构.例如,与您在 C++ 中可能发现的语义相比,C# 中的语义不同.大多数使用结构的程序员应该都使用过类,坦率地说,这样的问题毫无意义.

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. 从不.
    ...哦,你还在读书吗?你很执着.好的,好的.
  2. 当您明确需要值类型语义而不是引用类型语义时.
  3. 当您有一个非常小的类型时(经验法则是内存占用少于 16 字节).
  4. 当由您的结构表示的对象将是短暂的并且不可变(不会改变)时.
  5. 有时,为了与使用结构的本机代码进行互操作.

但如果您做出了知情决定并且真正相信您do,其实需要一个结构而不是一个类,你需要重温第二点,理解什么是值类型语义.Jon Skeet 的文章在这里 应该对澄清区别大有帮助.

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.

一旦你这样做了,你应该明白为什么在值类型 (struct) 中定义引用类型不是问题.引用类型就像指针.结构内部的字段不存储实际类型;相反,它存储指向该类型的指针(或引用).使用包含引用类型的字段声明结构体并没有任何矛盾或错误.它既不会减慢对象速度",也不会调用 GC",这是您在评论中表达的两个问题.

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.

这篇关于用引用类型成员定义结构体有意义吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆