我什么时候应该使用结构而不是类?
问题描述:
MSDN 说当你需要轻量级对象时你应该使用结构体.结构优于类时还有其他情况吗?
MSDN says that you should use structs when you need lightweight objects. Are there any other scenarios when a struct is preferable over a class?
有些人可能已经忘记了:
Some people might have forgotten that:
- 结构可以有方法.
- 结构不能被继承.
- structs can have methods.
- structs cannot be inherited.
我了解结构体和类之间的技术差异,只是我不太清楚何时使用结构体.
I understand the technical differences between structs and classes, I just don't have a good feel for when to use a struct.
答
MSDN 有答案:在类和结构之间进行选择.
基本上,该页面为您提供了一个 4 项清单,并说除非您的类型符合所有标准,否则请使用类.
Basically, that page gives you a 4-item checklist and says to use a class unless your type meets all of the criteria.
不要定义结构,除非类型具有以下所有内容特点:
Do not define a structure unless the type has all of the following characteristics:
- 它在逻辑上代表一个单一的值,类似于原始类型(整数、双精度等).
- 它的实例大小小于 16 字节.
- 它是不可变的.
- 不必经常装箱.