我何时使用struct而不是在c#中使用class?


When do I use struct instead of having class in c#?

本问题已经有最佳答案,请猛点这里访问。

Possible Duplicate:
When should I use a struct instead of a class?

由Venkat K C #网论坛。

09年07月29日:38

The only difference between"class" and"struct" is that a struct defaults to having public members (both data members and function members) and a struct defaults to public inheritance, whereas a class defaults to private members and private inheritance. That is the only difference. This difference can be circumvented by explicitly specifying"public", private", or"protected" so a struct can be made to act like a class in ever way and vice versa.by convention, most programmer's use"struct" for data types that have no member functions and that do not use inheritance. They use"class" for data types with member functions and inheritance. However, this is not necessary or even universallly acepted.

*(CAN这是真的)


当提到c时,这一说法完全是错误的。我相信C++可能是正确的,但是在C语言中,值类型(Struts)和引用类型(类)之间的区别。


您所引用的语句对于C++是正确的,但对于C++是不正确的。以下是C语言规范对结构所说内容的摘录:

Like classes, structs are data structures that can contain data members and function members, but unlike classes, structs are value types and do not require heap allocation. A variable of a struct type directly stores the data of the struct, whereas a variable of a class type stores a reference to a dynamically allocated object. Struct types do not support user-specified inheritance, and all struct types implicitly inherit from type object.

Structs are particularly useful for small data structures that have value semantics. Complex numbers, points in a coordinate system, or key-value pairs in a dictionary are all good examples of structs. The use of structs rather than classes for small data structures can make a large difference in the number of memory allocations an application performs.


这并不是唯一的区别。结构是值类型,类是引用类型。在谷歌上查一下,了解更多关于这些差异的信息,这些差异太多了,我现在无法列出。

除非,正如BrokenGlass指出的,它是C++。