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文章中的这四点似乎是一个很好的指导方针。

其他回答

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

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中的东西视为“扔掉的”,而将类中的东西视为更有用和“功能性的”

我认为最好的答案就是当你需要的是属性的集合时使用struct,当你需要的是属性和行为的集合时使用class。

✔️如果该类型的实例很小且通常存在时间很短,或者通常嵌入在其他对象中,请考虑定义一个结构而不是类。