结构(C# 编程指南)Structs (C# Programming Guide)

通过使用结构关键字来定义结构,例如:Structs are defined by using the struct keyword, for example:

public struct PostalAddress
{
    // Fields, properties, methods and events go here...
}

结构与类的大部分语法相同。Structs share most of the same syntax as classes. 结构名称必须是有效的 C# 标识符名称The name of the struct must be a valid C# identifier name. 结构在以下方面比类的限制更多:Structs are more limited than classes in the following ways:

  • 在结构声明中,除非将字段声明为 const 或 static,否则无法初始化。Within a struct declaration, fields cannot be initialized unless they are declared as const or static.
  • 结构不能声明无参数构造函数(没有参数的构造函数)或终结器。A struct cannot declare a parameterless constructor (a constructor without parameters) or a finalizer.
  • 结构在分配时进行复制。Structs are copied on assignment. 将结构分配给新变量时,将复制所有数据,并且对新副本所做的任何修改不会更改原始副本的数据。When a struct is assigned to a new variable, all the data is copied, and any modification to the new copy does not change the data for the original copy. 在处理值类型的集合(如 Dictionary<string, myStruct>)时,请务必记住这一点。This is important to remember when working with collections of value types such as Dictionary<string, myStruct>.
  • 结构是值类型,不同于类,类是引用类型。Structs are value types, unlike classes, which are reference types.
  • 与类不同,无需使用 new 运算符即可对结构进行实例化。Unlike classes, structs can be instantiated without using a new operator.
  • 结构可以声明具有参数的构造函数。Structs can declare constructors that have parameters.
  • 一个结构无法继承自另一个结构或类,并且它不能为类的基类。A struct cannot inherit from another struct or class, and it cannot be the base of a class. 所有结构都直接继承自 ValueType,后者继承自 ObjectAll structs inherit directly from ValueType, which inherits from Object.
  • 结构可以实现接口。A struct can implement interfaces.
  • 结构不能为 null,并且不能向结构变量分配 null,除非将变量声明为可为空的值类型。A struct cannot be null, and a struct variable cannot be assigned null unless the variable is declared as a nullable value type.

请参阅See also