C# 什么时候使用结构体?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/521298/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
When to use struct?
提问by Alex Baranosky
When should you use struct and not class in C#? My conceptual model is that structs are used in times when the item is merely a collection of value types. A way to logically hold them all together into a cohesive whole.
什么时候应该在 C# 中使用结构而不是类?我的概念模型是在项目仅仅是值类型的集合时使用结构。一种将它们合乎逻辑地组合成一个有凝聚力的整体的方法。
I came across these rules here:
我在这里遇到了这些规则:
- A struct should represent a single value.
- A struct should have a memory footprint less than 16 bytes.
- A struct should not be changed after creation.
- 一个结构体应该代表一个单一的值。
- 结构体的内存占用应小于 16 字节。
- 创建后不应更改结构。
Do these rules work? What does a struct mean semantically?
这些规则有效吗?结构体在语义上是什么意思?
回答by JoshBerke
Use a struct when you want value semantics as opposed to reference semantics.
当您需要值语义而不是引用语义时,请使用结构。
Edit
编辑
Not sure why folks are downvoting this but this is a valid point, and was made before the op clarified his question, and it is the most fundamental basic reason for a struct.
不知道为什么人们会反对这一点,但这是一个有效的观点,并且是在 op 澄清他的问题之前提出的,这是结构的最基本的基本原因。
If you need reference semantics you need a class not a struct.
如果您需要引用语义,则需要一个类而不是结构。
回答by dsimcha
Whenever you don't need polymorphism, want value semantics, and want to avoid heap allocation and the associated garbage collection overhead. The caveat, however, is that structs (arbitrarily large) are more expensive to pass around than class references (usually one machine word), so classes could end up being faster in practice.
当您不需要多态性、需要值语义并希望避免堆分配和相关的垃圾收集开销时。然而,需要注意的是,结构(任意大)的传递比类引用(通常是一个机器字)更昂贵,因此类在实践中最终可能会更快。
回答by Brian
I think a good first approximation is "never".
我认为一个好的第一个近似值是“从不”。
I think a good second approximation is "never".
我认为一个好的第二个近似值是“从不”。
If you are desperate for perf, consider them, but then always measure.
如果您非常渴望性能,请考虑它们,然后始终进行测量。
回答by Franci Penov
Structs are good for atomic representation of data, where the said data can be copied multiple times by the code. Cloning an object is in general more expensive than copying a struct, as it involves allocating the memory, running the constructor and deallocating/garbage collection when done with it.
结构体有利于数据的原子表示,其中所述数据可以被代码多次复制。克隆对象通常比复制结构更昂贵,因为它涉及分配内存、运行构造函数和在完成后释放/垃圾收集。
回答by Maurice Flanagan
You need to use a "struct" in situations where you want to explicitly specify memory layout using the StructLayoutAttribute- typically for PInvoke.
在您想要使用StructLayoutAttribute显式指定内存布局的情况下,您需要使用“结构” - 通常用于 PInvoke。
Edit: Comment points out that you can use class or struct with StructLayoutAttribute and that is certainly true. In practice, you would typically use a struct - it is allocated on the stack vs the heap which makes sense if you are just passing an argument to an unmanaged method call.
编辑:评论指出您可以将类或结构与 StructLayoutAttribute 一起使用,这当然是正确的。在实践中,您通常会使用一个结构体——它是在堆栈上与堆上分配的,如果您只是将参数传递给非托管方法调用,这很有意义。
回答by BC.
First: Interop scenarios or when you need to specify the memory layout
第一:互操作场景或需要指定内存布局时
Second: When the data is almost the same size as a reference pointer anyway.
第二:当数据与引用指针的大小几乎相同时。
回答by leppie
With the exception of the valuetypes that are used directly by the runtime and various others for PInvoke purposes, you should only use valuetypes in 2 scenarios.
除了运行时直接使用的值类型和其他各种用于 PInvoke 目的的值类型之外,您应该只在 2 个场景中使用值类型。
- When you need copy semantics.
- When you need automatic initialization, normally in arrays of these types.
- 当您需要复制语义时。
- 当您需要自动初始化时,通常在这些类型的数组中。
回答by mjfgates
I use structs for packing or unpacking any sort of binary communication format. That includes reading or writing to disk, DirectX vertex lists, network protocols, or dealing with encrypted/compressed data.
我使用结构来打包或解包任何类型的二进制通信格式。这包括读取或写入磁盘、DirectX 顶点列表、网络协议或处理加密/压缩数据。
The three guidelines you list haven't been useful for me in this context. When I need to write out four hundred bytes of stuff in a Particular Order, I'm gonna define a four-hundred-byte struct, and I'm gonna fill it with whatever unrelated values it's supposed to have, and I'm going to set it up whatever way makes the most sense at the time. (Okay, four hundred bytes would be pretty strange-- but back when I was writing Excel files for a living, I was dealing with structs of up to about forty bytes all over, because that's how big some of the BIFF records ARE.)
在这种情况下,您列出的三个指南对我没有用。当我需要以特定顺序写出四百字节的东西时,我将定义一个四百字节的结构,我将用它应该具有的任何不相关的值填充它,然后我将以当时最有意义的方式设置它。(好吧,四百个字节会很奇怪——但是当我以编写 Excel 文件为生时,我处理的结构多达大约 40 个字节,因为这就是一些 BIFF 记录的大小。)
回答by SnapJag
Nah - I don't entirely agree with the rules. They are good guidelines to consider with performance and standardization, but not in light of the possibilities.
不 - 我不完全同意规则。它们是在性能和标准化方面考虑的很好的指导方针,但不是考虑到可能性。
As you can see in the responses, there are a lot of creative ways to use them. So, these guidelines need to just be that, always for the sake of performance and efficiency.
正如您在回复中看到的那样,有很多创造性的方法可以使用它们。因此,这些指导方针必须始终是为了性能和效率。
In this case, I use classes to represent real world objects in their larger form, I use structs to represent smaller objects that have more exact uses. The way you said it, "a more cohesive whole." The keyword being cohesive. The classes will be more object oriented elements, while structs can have some of those characteristics, though on a smaller scale. IMO.
在这种情况下,我使用类来表示更大形式的现实世界对象,我使用结构来表示具有更精确用途的较小对象。就像你说的那样,“一个更有凝聚力的整体。” 关键字是有凝聚力的。类将是更多面向对象的元素,而结构可以具有其中一些特征,尽管规模较小。海事组织。
I use them a lot in Treeview and Listview tags where common static attributes can be accessed very quickly. I have always struggled to get this info another way. For example, in my database applications, I use a Treeview where I have Tables, SPs, Functions, or any other objects. I create and populate my struct, put it in the tag, pull it out, get the data of the selection and so forth. I wouldn't do this with a class!
我在 Treeview 和 Listview 标签中经常使用它们,在这些标签中可以非常快速地访问常见的静态属性。我一直在努力以另一种方式获取这些信息。例如,在我的数据库应用程序中,我使用树视图,其中包含表、SP、函数或任何其他对象。我创建并填充我的结构,将其放入标签中,将其拉出,获取选择的数据等等。我不会在课堂上这样做!
I do try and keep them small, use them in single instance situations, and keep them from changing. It's prudent to be aware of memory, allocation, and performance. And testing is so necessary.
我确实尝试让它们变小,在单实例情况下使用它们,并防止它们发生变化。注意内存、分配和性能是明智的。测试是非常必要的。
回答by SnapJag
I rarely use a struct for things. But that's just me. It depends whether I need the object to be nullable or not.
我很少对事物使用结构。但这只是我。这取决于我是否需要对象可以为空。
As stated in other answers, I use classes for real-world objects. I also have the mindset of structs are used for storing small amounts of data.
正如其他答案中所述,我将类用于现实世界的对象。我也有结构用于存储少量数据的心态。