值类型(C# 参考)Value types (C# reference)

值类型 和引用类型是 C# 类型的两个主要类别。Value types and reference types are the two main categories of C# types. 值类型的变量包含类型的实例。A variable of a value type contains an instance of the type. 它不同于引用类型的变量,后者包含对类型实例的引用。This differs from a variable of a reference type, which contains a reference to an instance of the type. 默认情况下,在分配中,通过将实参传递给方法并返回方法结果来复制变量值。By default, on assignment, passing an argument to a method, and returning a method result, variable values are copied. 对于值类型变量,会复制相应的类型实例。In the case of value-type variables, the corresponding type instances are copied. 以下示例演示了该行为:The following example demonstrates that behavior:

using System;

public struct MutablePoint
{
    public int X;
    public int Y;

    public MutablePoint(int x, int y) => (X, Y) = (x, y);

    public override string ToString() => $"({X}, {Y})";
}

public class Program
{
    public static void Main()
    {
        var p1 = new MutablePoint(1, 2);
        var p2 = p1;
        p2.Y = 200;
        Console.WriteLine($"{nameof(p1)} after {nameof(p2)} is modified: {p1}");
        Console.WriteLine($"{nameof(p2)}: {p2}");

        MutateAndDisplay(p2);
        Console.WriteLine($"{nameof(p2)} after passing to a method: {p2}");
    }

    private static void MutateAndDisplay(MutablePoint p)
    {
        p.X = 100;
        Console.WriteLine($"Point mutated in a method: {p}");
    }
}
// Expected output:
// p1 after p2 is modified: (1, 2)
// p2: (1, 200)
// Point mutated in a method: (100, 200)
// p2 after passing to a method: (1, 200)

如前面的示例所示,对值类型变量的操作只影响存储在变量中的值类型实例。As the preceding example shows, operations on a value-type variable affect only that instance of the value type, stored in the variable.

如果值类型包含引用类型的数据成员,则在复制值类型实例时,只会复制对引用类型实例的引用。If a value type contains a data member of a reference type, only the reference to the instance of the reference type is copied when a value-type instance is copied. 副本和原始值类型实例都具有对同一引用类型实例的访问权限。Both the copy and original value-type instance have access to the same reference-type instance. 以下示例演示了该行为:The following example demonstrates that behavior:

using System;
using System.Collections.Generic;

public struct TaggedInteger
{
    public int Number;
    private List<string> tags;

    public TaggedInteger(int n)
    {
        Number = n;
        tags = new List<string>();
    }

    public void AddTag(string tag) => tags.Add(tag);

    public override string ToString() => $"{Number} [{string.Join(", ", tags)}]";
}

public class Program
{
    public static void Main()
    {
        var n1 = new TaggedInteger(0);
        n1.AddTag("A");
        Console.WriteLine(n1);  // output: 0 [A]

        var n2 = n1;
        n2.Number = 7;
        n2.AddTag("B");

        Console.WriteLine(n1);  // output: 0 [A, B]
        Console.WriteLine(n2);  // output: 7 [A, B]
    }
}

备注

若要使代码更不易出错、更可靠,请定义并使用不可变的值类型。To make your code less error-prone and more robust, define and use immutable value types. 本文仅为演示目的使用可变值类型。This article uses mutable value types only for demonstration purposes.

值类型的种类Kinds of value types

值类型可以是以下种类之一:A value type can be one of the two following kinds:

  • 结构类型,用于封装数据和相关功能a structure type, which encapsulates data and related functionality
  • 枚举类型,由一组命名常数定义,表示一个选择或选择组合an enumeration type, which is defined by a set of named constants and represents a choice or a combination of choices

可为 null 值类型 T? 表示其基础值类型 T 的所有值及额外的 null 值。A nullable value type T? represents all values of its underlying value type T and an additional null value. 不能将 null 分配给值类型的变量,除非它是可为 null 的值类型。You cannot assign null to a variable of a value type, unless it's a nullable value type.

内置值类型Built-in value types

C# 提供以下内置值类型,也称为“简单类型” :C# provides the following built-in value types, also known as simple types:

所有简单值都是结构类型,它们与其他结构类型的不同之处在于,它们允许特定的额外操作:All simple types are structure types and differ from other structure types in that they permit certain additional operations:

  • 可以使用文字为简单类型提供值。You can use literals to provide a value of a simple type. 例如,'A' 是类型 char 的文本,2001 是类型 int 的文本。For example, 'A' is a literal of the type char and 2001 is a literal of the type int.

  • 可以使用 const 关键字声明简单类型的常数。You can declare constants of the simple types with the const keyword. 不能具有其他结构类型的常数。It's not possible to have constants of other structure types.

  • 常数表达式的操作数都是简单类型的常数,在编译时进行评估。Constant expressions, whose operands are all constants of the simple types, are evaluated at compile time.

从 C# 7.0 开始,C# 支持值元组Beginning with C# 7.0, C# supports value tuples. 值元组是值类型,而不是简单类型。A value tuple is a value type, but not a simple type.

C# 语言规范C# language specification

有关更多信息,请参阅 C# 语言规范的以下部分:For more information, see the following sections of the C# language specification:

请参阅See also