什么时候应该使用一个struct而不是一个类? [英] When should I use a struct instead of a class?
本文介绍了什么时候应该使用一个struct而不是一个类?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
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?
编辑:
有些人忘记了:
1. 结构可以有方法!
2. 结构没有继承能力。
Some people have forgotten that:
1. structs can have methods!
2. structs have no inheritance capabilites.
另一个编辑
我明白了技术上的差异,对于 WHEN 使用结构。
推荐答案
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字节。
- 这是不可变的。
- 不必频繁地被盒装。 li>
- It logically represents a single value, similar to primitive types (integer, double, and so on).
- It has an instance size smaller than 16 bytes.
- It is immutable.
- It will not have to be boxed frequently.
这篇关于什么时候应该使用一个struct而不是一个类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文