MSDN说当需要轻量级对象时应该使用结构。在其他情况下,结构体比类更可取吗?

有些人可能已经忘记了:

结构可以有方法。 结构不能被继承。

我理解结构体和类之间的技术差异,我只是对什么时候使用结构体没有很好的感觉。


当前回答

我会在以下情况下使用结构体:

an object is supposed to be read only(every time you pass/assign a struct it gets copied). Read only objects are great when it comes to multithreaded processing as they don't requite locking in most cases. an object is small and short-living. In such a case there is a good chance that the object will be allocated on the stack which is much more efficient than putting it on the managed heap. What is more the memory allocated by the object will be freed as soon as it goes outside its scope. In other words it's less work for Garbage Collector and the memory is used more efficient.

其他回答

当我想要将几个值组合在一起以从方法调用中传递内容时,我总是使用结构体,但在读取这些值之后,我将不需要将它用于任何事情。只是为了保持干净。我倾向于将struct中的东西视为“扔掉的”,而将类中的东西视为更有用和“功能性的”

Bill Wagner在他的书《effective c#》(http://www.amazon.com/Effective-Specific-Ways-Improve-Your/dp/0321245660)中有一章是关于这个的。他总结了以下原则:

类型数据存储的主要职责是什么? 它的公共接口是否完全由访问或修改其数据成员的属性定义? 你确定你的类型永远不会有子类吗? 您确定您的类型永远不会被多态处理吗? 如果你对4个问题都回答“是”,请使用结构体。否则,使用 类。

结构体在堆栈上而不是堆上因此它们是线程安全的,应该在实现传输对象模式时使用,你永远不想在堆上使用对象它们是易变的,在这种情况下你想使用调用堆栈,这是使用结构体的基本情况我对这里的答案感到惊讶,

除了以上精彩的回答:

结构是值类型。

它们永远不能被设置为“无”。

设置一个结构= Nothing,将其所有的值类型设置为默认值。

正如@Simon所说,结构体提供了“值类型”语义,所以如果你需要类似于内置数据类型的行为,可以使用结构体。由于结构体是通过复制传递的,所以要确保它们的大小很小,大约16字节。