类型和变量Types and variables

C# 有两种类型:值类型引用类型There are two kinds of types in C#: value types and reference types. 值类型的变量直接包含数据,而引用类型的变量则存储对数据(称为“对象”)的引用。Variables of value types directly contain their data whereas variables of reference types store references to their data, the latter being known as objects. 对于引用类型,两个变量可以引用同一对象;因此,对一个变量执行的运算可能会影响另一个变量引用的对象。With reference types, it is possible for two variables to reference the same object and thus possible for operations on one variable to affect the object referenced by the other variable. 借助值类型,每个变量都有自己的数据副本;因此,对一个变量执行的运算不会影响另一个变量(refout 参数变量除外)。With value types, the variables each have their own copy of the data, and it is not possible for operations on one to affect the other (except in the case of ref and out parameter variables).

C# 值类型又细分为简单类型枚举类型结构类型可以为 null 的值类型C#’s value types are further divided into simple types, enum types, struct types, and nullable value types. C# 引用类型又细分为类类型接口类型数组类型委托类型C#’s reference types are further divided into class types, interface types, array types, and delegate types.

下面概述了 C# 的类型系统。The following provides an overview of C#’s type system.

  • 值类型Value types
    • 简单类型Simple types
      • 有符号的整型:sbyteshortintlongSigned integral: sbyte, short, int, long
      • 无符号的整型:byteushortuintulongUnsigned integral: byte, ushort, uint, ulong
      • Unicode 字符:charUnicode characters: char
      • IEEE 二进制浮点:floatdoubleIEEE binary floating-point: float, double
      • 高精度十进制浮点数:decimalHigh-precision decimal floating-point: decimal
      • 布尔:boolBoolean: bool
    • 枚举类型Enum types
      • 格式为 enum E {...} 的用户定义类型User-defined types of the form enum E {...}
    • 结构类型Struct types
      • 格式为 struct S {...} 的用户定义类型User-defined types of the form struct S {...}
    • 可以为 null 的值类型Nullable value types
      • 值为 null 的其他所有值类型的扩展Extensions of all other value types with a null value
  • 引用类型Reference types
    • 类类型Class types
      • 其他所有类型的最终基类:objectUltimate base class of all other types: object
      • Unicode 字符串:stringUnicode strings: string
      • 格式为 class C {...} 的用户定义类型User-defined types of the form class C {...}
    • 接口类型Interface types
      • 格式为 interface I {...} 的用户定义类型User-defined types of the form interface I {...}
    • 数组类型Array types
      • 一维和多维,例如 int[]int[,]Single- and multi-dimensional, for example, int[] and int[,]
    • 委托类型Delegate types
      • 格式为 delegate int D(...) 的用户定义类型User-defined types of the form delegate int D(...)

有关数值类型的详细信息,请参阅整型类型浮点类型表For more information about numeric types, see Integral types and Floating-point types table.

C# 的 bool 类型用于表示布尔值(truefalse)。C#’s bool type is used to represent Boolean values—values that are either true or false.

C# 使用 Unicode 编码处理字符和字符串。Character and string processing in C# uses Unicode encoding. char 类型表示 UTF-16 代码单元,string 类型表示一系列 UTF-16 代码单元。The char type represents a UTF-16 code unit, and the string type represents a sequence of UTF-16 code units.

C# 程序使用类型声明创建新类型。C# programs use type declarations to create new types. 类型声明指定新类型的名称和成员。A type declaration specifies the name and the members of the new type. 用户可定义以下五种 C# 类型:类类型、结构类型、接口类型、枚举类型和委托类型。Five of C#’s categories of types are user-definable: class types, struct types, interface types, enum types, and delegate types.

class 类型定义包含数据成员(字段)和函数成员(方法、属性及其他)的数据结构。A class type defines a data structure that contains data members (fields) and function members (methods, properties, and others). 类类型支持单一继承和多形性,即派生类可以扩展和专门针对基类的机制。Class types support single inheritance and polymorphism, mechanisms whereby derived classes can extend and specialize base classes.

struct 类型定义包含数据成员和函数成员的结构,这一点与类类型相似。A struct type is similar to a class type in that it represents a structure with data members and function members. 不过,与类不同的是,结构是值类型,通常不需要进行堆分配。However, unlike classes, structs are value types and do not typically require heap allocation. 结构类型不支持用户指定的继承,并且所有结构类型均隐式继承自类型 objectStruct types do not support user-specified inheritance, and all struct types implicitly inherit from type object.

interface 类型将协定定义为一组已命名的公共函数成员。An interface type defines a contract as a named set of public function members. 实现 interfaceclassstruct 必须提供接口函数成员的实现代码。A class or struct that implements an interface must provide implementations of the interface’s function members. interface 可以继承自多个基接口,classstruct 可以实现多个接口。An interface may inherit from multiple base interfaces, and a class or struct may implement multiple interfaces.

delegate 类型表示引用包含特定参数列表和返回类型的方法。A delegate type represents references to methods with a particular parameter list and return type. 通过委托,可以将方法视为可分配给变量并可作为参数传递的实体。Delegates make it possible to treat methods as entities that can be assigned to variables and passed as parameters. 委托类同于函数式语言提供的函数类型。Delegates are analogous to function types provided by functional languages. 委托也类似于其他一些语言中的函数指针概念,但与函数指针不同的是,委托不仅面向对象,还类型安全。They are also similar to the concept of function pointers found in some other languages, but unlike function pointers, delegates are object-oriented and type-safe.

classstructinterfacedelegate 类型全部都支持泛型,因此可以使用其他类型对它们进行参数化。The class, struct, interface and delegate types all support generics, whereby they can be parameterized with other types.

enum 类型是一种包含已命名常量的独特类型。An enum type is a distinct type with named constants. 每个 enum 类型都有一个基础类型(必须是八种整型类型之一)。Every enum type has an underlying type, which must be one of the eight integral types. enum 类型的值集与基础类型的值集相同。The set of values of an enum type is the same as the set of values of the underlying type.

C# 支持任意类型的一维和多维数组。C# supports single- and multi-dimensional arrays of any type. 与上述类型不同,数组类型无需先声明即可使用。Unlike the types listed above, array types do not have to be declared before they can be used. 相反,数组类型是通过在类型名称后面添加方括号构造而成。Instead, array types are constructed by following a type name with square brackets. 例如,int[]int 类型的一维数组,int[,]int 类型的二维数组,int[][] 是由 int 类型的一维数组构成的一维数组。For example, int[] is a single-dimensional array of int, int[,] is a two-dimensional array of int, and int[][] is a single-dimensional array of single-dimensional array of int.

可以为 null 的值类型也无需先声明即可使用。Nullable value types also do not have to be declared before they can be used. 对于所有不可以为 null 的值类型 T,都有对应的可以为 null 的值类型 T?,后者可以包含附加值 nullFor each non-nullable value type T there is a corresponding nullable value type T?, which can hold an additional value, null. 例如,int? 是可以包含任何 32 位整数或值 null 的类型。For instance, int? is a type that can hold any 32-bit integer or the value null.

C# 采用统一的类型系统,因此任意类型的值都可视为 objectC#’s type system is unified such that a value of any type can be treated as an object. 每种 C# 类型都直接或间接地派生自 object 类类型,而 object 是所有类型的最终基类。Every type in C# directly or indirectly derives from the object class type, and object is the ultimate base class of all types. 只需将值视为类型 object,即可将引用类型的值视为对象。Values of reference types are treated as objects simply by viewing the values as type object. 通过执行装箱取消装箱操作,可以将值类型的值视为对象。Values of value types are treated as objects by performing boxing and unboxing operations. 在以下示例中,int 值被转换成 object,然后又恢复成 intIn the following example, an int value is converted to object and back again to int.

using System;
class BoxingExample
{
    static void Main()
    {
        int i = 123;
        object o = i;    // Boxing
        int j = (int)o;  // Unboxing
    }
}

当值类型的值转换成 object 类型时,将分配 object 实例(亦称为“箱”)来包含值,然后该值会复制到相应的箱中。When a value of a value type is converted to type object, an object instance, also called a "box", is allocated to hold the value, and the value is copied into that box. 相反,当 object 引用被显式转换成值类型时,将检查引用的 object 是否是具有正确值类型的箱;如果检查成功,则会将箱中的值复制出来。Conversely, when an object reference is cast to a value type, a check is made that the referenced object is a box of the correct value type, and, if the check succeeds, the value in the box is copied out.

C# 的统一类型系统实际上意味着可以“按需”将值类型转换成对象。C#’s unified type system effectively means that value types can become objects "on demand." 鉴于这种统一性,使用类型 object 的常规用途库可以与引用类型和值类型结合使用。Because of the unification, general-purpose libraries that use type object can be used with both reference types and value types.

C# 有多种变量,其中包括字段、数组元素、局部变量和参数。There are several kinds of variables in C#, including fields, array elements, local variables, and parameters. 变量表示存储位置,每个变量都具有一种类型,用于确定可以在变量中存储哪些值,如下文所述。Variables represent storage locations, and every variable has a type that determines what values can be stored in the variable, as shown below.

  • 不可以为 null 的值类型Non-nullable value type
    • 具有精确类型的值A value of that exact type
  • 可以为 null 的值类型Nullable value type
    • null 值或具有精确类型的值A null value or a value of that exact type
  • objectobject
    • null 引用、对任意引用类型的对象的引用,或对任意值类型的装箱值的引用A null reference, a reference to an object of any reference type, or a reference to a boxed value of any value type
  • 类类型Class type
    • null 引用、对类类型实例的引用,或对派生自类类型的类实例的引用A null reference, a reference to an instance of that class type, or a reference to an instance of a class derived from that class type
  • 接口类型Interface type
    • null 引用、对实现接口类型的类类型实例的引用,或对实现接口类型的值类型的装箱值的引用A null reference, a reference to an instance of a class type that implements that interface type, or a reference to a boxed value of a value type that implements that interface type
  • 数组类型Array type
    • null 引用、对数组类型实例的引用,或对兼容的数组类型实例的引用A null reference, a reference to an instance of that array type, or a reference to an instance of a compatible array type
  • 委托类型Delegate type
    • null 引用或对兼容的委托类型实例的引用A null reference or a reference to an instance of a compatible delegate type