优秀的编程知识分享平台

网站首页 > 技术文章 正文

如何在 C# 中创建一个不可变的变量?

nanyue 2025-01-26 23:39:47 技术文章 7 ℃

在 C# 中,创建一个不可变的变量可以通过以下几种方式实现:


1. 使用readonly关键字

  • readonly 修饰符用于声明在类或结构中只能在初始化构造函数中赋值的字段。
  • 一旦被赋值,它的值不能更改。

示例

class Example
{
    public readonly int ImmutableValue;

    public Example(int value)
    {
        ImmutableValue = value; // 只能在构造函数中赋值
    }
}
Example example = new Example(10);
// example.ImmutableValue = 20; // 编译错误:readonly 字段不能被重新赋值

2. 使用const关键字

  • const 声明的变量在编译时必须被赋值,并且其值在运行时不能更改。
  • 只能用于修饰静态常量,通常用于声明程序中不会改变的值。

示例

public class Constants
{
    public const double Pi = 3.14159;
}
double circumference = 2 * Constants.Pi * radius;

注意

  • const 值只能是编译时确定的常量值。
  • const 默认是静态的(即可以通过类名直接访问,无需实例化)。

3. 使用init访问器

  • init 是 C# 9.0 引入的一种新特性,用于定义只能在对象初始化时赋值的属性。
  • 这种方式可以用于定义不可变的对象。

示例

public class Person
{
    public string Name { get; init; }
    public int Age { get; init; }
}

var person = new Person { Name = "John", Age = 30 };
// person.Age = 40; // 编译错误:init 属性只能在初始化时赋值

4. 使用readonly struct

  • 使用 readonly 关键字声明的结构体,其所有字段在初始化后不可变。
  • 常用于表示不可变的值对象。

示例

public readonly struct Point
{
    public Point(int x, int y)
    {
        X = x;
        Y = y;
    }
    public int X { get; }
    public int Y { get; }
}

var point = new Point(10, 20);
// point.X = 30; // 编译错误:无法为只读属性赋值

5. 使用不可变类型(如System.Collections.Immutable)

  • 对于集合类型,可以使用 System.Collections.Immutable 提供的不可变集合。
  • 这些集合一旦创建,内容不可更改。

示例

using System.Collections.Immutable;

var immutableList = ImmutableList.Create(1, 2, 3);
// immutableList.Add(4); // 编译错误:集合是不可变的

总结

方法

特点

const

编译时常量,运行时不能更改。

readonly

初始化或构造函数内赋值后不可更改。

init 访问器

用于属性的不可变赋值,适用于初始化阶段。

readonly struct

不可变结构体,所有字段初始化后不能更改。

不可变集合

使用 System.Collections.Immutable 实现不可变集合(如 ImmutableList)。

根据需求选择适当的方式来创建不可变变量。

Tags:

最近发表
标签列表