什么时候应该使用一个类的结构呢?什么时候、结构

2023-09-02 10:14:53 作者:追逐你日夜不断

MSDN说,你应该使用结构,当您需要轻量级对象。是否有任何其他情况下,当一个结构是preferable过班?

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. 结构的有产业capabilites。

Some people have forgotten that: 1. structs can have methods! 2. structs have no inheritance capabilites.

另一个编辑: 据我所知,技术上的差异,我只是没有一个很好的感觉的在的使用结构。

Another I understand the technical differences, I just don't have a good feel for WHEN to use a struct.

推荐答案

MSDN有答案: 选择类和结构的关系。

MSDN has the answer: Choosing Between Classes and Structures.

基本上,该页面为您提供了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:   这在逻辑上重新presents一个值,类似于原始类型   (整数,双,等)。   在它有一个实例大小小于16字节小。   这是不可改变的。   它不会必须频繁装箱。    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.

 
精彩推荐