转:struct和class区别小结

来源:互联网 发布:重庆seo基础入门 编辑:程序博客网 时间:2024/05/17 07:28

A struct is similar to a class, with the following major differences:

A class is a reference type, while a struct is a value type. Consequently, structs are typically used to express simple types, in which value-type semantics are desirable (e.g., assignment copies a value rather than a reference).

A class fully supports inheritance , whereas a struct can inherit only from an object and is implicitly sealed (in the runtime structs actually inherit from System.ValueType). Both classes and structs can implement interfaces.

A class can have a destructor, and a struct cannot.

A class can define a custom parameterless constructor and initialize instance fields, while a struct cannot. The default parameterless constructor for a struct initializes each field with a default value (effectively zero). If a struct declares a constructor(s), then all of its fields must be assigned in that constructor call.

结构具有以下特点:

  • 结构是值类型,而类是引用类型。
  • 向方法传递结构时,结构是通过传值方式传递的,而不是作为引用传递的。
  • 与类不同,结构的实例化可以不使用 new 运算符。
  • 结构可以声明构造函数,但它们必须带参数。
  • 一个结构不能从另一个结构或类继承,而且不能作为一个类的基。
  • 所有结构都直接继承自 System.ValueType,后者继承自 System.Object。
  • 结构可以实现接口。

本文来自CSDN博客,转载请标明出处:http://blog.csdn.net/changesway/archive/2008/10/28/3165141.aspx

原创粉丝点击