MSDN说当需要轻量级对象时应该使用结构。在其他情况下,结构体比类更可取吗?
有些人可能已经忘记了:
结构可以有方法。 结构不能被继承。
我理解结构体和类之间的技术差异,我只是对什么时候使用结构体没有很好的感觉。
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.
其他回答
当您不需要行为,但需要比简单的数组或字典更多的结构时。
跟进 这就是我对结构体的一般看法。我知道他们可以有方法,但我喜欢保持整体的精神区分。
我会在以下情况下使用结构体:
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.
结构体在堆栈上而不是堆上因此它们是线程安全的,应该在实现传输对象模式时使用,你永远不想在堆上使用对象它们是易变的,在这种情况下你想使用调用堆栈,这是使用结构体的基本情况我对这里的答案感到惊讶,
✔️如果该类型的实例很小且通常存在时间很短,或者通常嵌入在其他对象中,请考虑定义一个结构而不是类。
除了以上精彩的回答:
结构是值类型。
它们永远不能被设置为“无”。
设置一个结构= Nothing,将其所有的值类型设置为默认值。