MSDN说当需要轻量级对象时应该使用结构。在其他情况下,结构体比类更可取吗?
有些人可能已经忘记了:
结构可以有方法。 结构不能被继承。
我理解结构体和类之间的技术差异,我只是对什么时候使用结构体没有很好的感觉。
MSDN说当需要轻量级对象时应该使用结构。在其他情况下,结构体比类更可取吗?
有些人可能已经忘记了:
结构可以有方法。 结构不能被继承。
我理解结构体和类之间的技术差异,我只是对什么时候使用结构体没有很好的感觉。
当前回答
嗯…
I wouldn't use garbage collection as an argument for/against the use of structs vs classes. The managed heap works much like a stack - creating an object just puts it at the top of the heap, which is almost as fast as allocating on the stack. Additionally, if an object is short-lived and does not survive a GC cycle, deallocation is free as the GC only works with memory that's still accessible. (Search MSDN, there's a series of articles on .NET memory management, I'm just too lazy to go dig for them).
大多数情况下,我使用结构体时,都会后悔这样做,因为我后来发现使用引用语义会让事情更简单一些。
无论如何,上面的MSDN文章中的这四点似乎是一个很好的指导方针。
其他回答
我认为最好的答案就是当你需要的是属性的集合时使用struct,当你需要的是属性和行为的集合时使用class。
我会在以下情况下使用结构体:
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中的东西视为“扔掉的”,而将类中的东西视为更有用和“功能性的”
除了以上精彩的回答:
结构是值类型。
它们永远不能被设置为“无”。
设置一个结构= Nothing,将其所有的值类型设置为默认值。
Bill Wagner在他的书《effective c#》(http://www.amazon.com/Effective-Specific-Ways-Improve-Your/dp/0321245660)中有一章是关于这个的。他总结了以下原则:
类型数据存储的主要职责是什么? 它的公共接口是否完全由访问或修改其数据成员的属性定义? 你确定你的类型永远不会有子类吗? 您确定您的类型永远不会被多态处理吗? 如果你对4个问题都回答“是”,请使用结构体。否则,使用 类。