MSDN说当需要轻量级对象时应该使用结构。在其他情况下,结构体比类更可取吗?
有些人可能已经忘记了:
结构可以有方法。 结构不能被继承。
我理解结构体和类之间的技术差异,我只是对什么时候使用结构体没有很好的感觉。
MSDN说当需要轻量级对象时应该使用结构。在其他情况下,结构体比类更可取吗?
有些人可能已经忘记了:
结构可以有方法。 结构不能被继承。
我理解结构体和类之间的技术差异,我只是对什么时候使用结构体没有很好的感觉。
当前回答
当您不需要行为,但需要比简单的数组或字典更多的结构时。
跟进 这就是我对结构体的一般看法。我知道他们可以有方法,但我喜欢保持整体的精神区分。
其他回答
✔️如果该类型的实例很小且通常存在时间很短,或者通常嵌入在其他对象中,请考虑定义一个结构而不是类。
当您需要值类型语义而不是引用类型时,请使用结构。结构体是按值复制的,所以要小心!
另见以前的问题,例如:
.NET中struct和class的区别是什么?
在以下情况下使用类:
它的身份很重要。结构在按值传递给方法时被隐式复制。 它将占用大量内存。 它的字段需要初始化式。 你需要从基类继承。 你需要多态行为;
在以下情况下使用结构:
It will act like a primitive type (int, long, byte, etc.). It must have a small memory footprint. You are calling a P/Invoke method that requires a structure to be passed in by value. You need to reduce the impact of garbage collection on application performance. Its fields need to be initialized only to their default values. This value would be zero for numeric types, false for Boolean types, and null for reference types. Note that in C# 6.0 structs can have a default constructor that can be used to initialize the struct’s fields to nondefault values. You do not need to inherit from a base class (other than ValueType, from which all structs inherit). You do not need polymorphic behavior.
嗯…
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。