C#修饰符readonly和const

2019-08-27  本文已影响0人  86a262e62b0b

参考:


区别:

一. const

1. 特点:

class Calendar1
{
    public const int Months = 12;
}

在此示例中,常量 Months 始终为 12,即使类本身也无法更改它。 实际上,当编译器遇到 C# 源代码中的常量标识符(例如Months )时,它直接将文本值替换到它生成的中间语言 (IL) 代码中。 因为运行时没有与常量相关联的变量地址,所以 const 字段不能通过引用传递,并且不能作为l-value在表达式中显示。

int birthstones = Calendar.Months;

二. readonly

1. 使用

readonly关键字是一个可在三个上下文中使用的修饰符:

(1)在字段申明中,readonly可以在字段声明和构造函数中多次分配、重新分配。构造函数退出后,不能分配 readonly 字段。
其中readonly在值类型和引用类型具有不同的含义:

2. Readonly struct example

public readonly struct Point
{
    public double X { get; }
    public double Y { get; }

    public Point(double x, double y) => (X, Y) = (x, y);

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

前面的示例使用只读自动属性来声明其存储。 该操作指示编译器为这些属性创建 readonly 支持字段。 还可以直接声明 readonly 字段:

public readonly struct Point
{
    public readonly double X;
    public readonly double Y;

    public Point(double x, double y) => (X, Y) = (x, y);

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

3. Ref readonly return example

private static readonly Point origin = new Point(0, 0);
public static ref readonly Point Origin => ref origin;

所返回的类型不需要为 readonly struct。 ref 能返回的任何类型都能由 ref readonly 返回。

上一篇 下一篇

猜你喜欢

热点阅读