结构和类

Posted on 2006-05-16 16:25  太阳天子  阅读(250)  评论(0)    收藏  举报

结构和类
结构是使用 struct 关键字定义的,例如:

C#  CopyCode image复制代码
public struct PostalAddress
            {
            // Fields, properties, methods and events go here...
            }
            

结构与类共享几乎所有相同的语法,但结构比类受到的限制更多:

  • 尽管结构的静态字段可以初始化,结构实例字段声明还是不能使用初始值设定项。

  • 结构不能声明默认构造函数(没有参数的构造函数)或析构函数。

结构的副本由编译器自动创建和销毁,因此不需要使用默认构造函数和析构函数。实际上,编译器通过为所有字段赋予默认值(参见默认值表)来实现默认构造函数。结构不能从类或其他结构继承。

结构是值类型 -- 如果从结构创建一个对象并将该对象赋给某个变量,变量则包含结构的全部值。复制包含结构的变量时,将复制所有数据,对新副本所做的任何修改都不会改变旧副本的数据。由于结构不使用引用,因此结构没有标识 -- 具有相同数据的两个值类型实例是无法区分的。C# 中的所有值类型本质上都继承自 ValueType,后者继承自 Object

编译器可以在一个称为装箱的过程中将值类型转换为引用类型。有关更多信息,请参见装箱和取消装箱

结构概述

结构具有以下特点:

  • 结构是值类型,而类是引用类型。

  • 向方法传递结构时,结构是通过传值方式传递的,而不是作为引用传递的。

  • 与类不同,结构的实例化可以不使用 new 运算符。

  • 结构可以声明构造函数,但它们必须带参数。

  • 一个结构不能从另一个结构或类继承,而且不能作为一个类的基。所有结构都直接继承自 System.ValueType,后者继承自 System.Object

  • 结构可以实现接口。

  • 在结构中初始化实例字段是错误的。


  1. What is the difference between a struct and a class in C#? - From language spec: The list of similarities between classes and structs is as follows. Longstructs can implement interfaces and can have the same kinds of members as classes. Structs differ from classes in several important ways; however, structs are value types rather than reference types, and inheritance is not supported for structs. Struct values are stored on the stack or in-line. Careful programmers can sometimes enhance performance through judicious use of structs. For example, the use of a struct rather than a class for a Point can make a large difference in the number of memory allocations performed at runtime. The program below creates and initializes an array of 100 points. With Point implemented as a class, 101 separate objects are instantiated-one for the array and one each for the 100 elements.

博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3