属性 和 readonly getter 有什么好处?

What's the benefit of a property with readonly getter?

我已经多次看到 readonly(通常是针对成员,但也在只读结构的上下文中)。

但我第一次看到的是组合 readonly get for a 属性:

private double _x;
public double X
{
    readonly get => _x;
    set => _x = value;
}

但这是什么意思?指定 getter readonly 的限制到底是什么?

这不是有效的 C# 代码。检查任何编译器都会得到你:

The modifier readonly is not valid for this item

那是因为 getter 和 setter 只是函数的语法糖。

对于 类 你确实是对的,只读 getter 没有意义,因为只读函数没有意义。只有不提供 setter.

变量才具有只读点和属性

https://dotnetfiddle.net/SPhTR8

对于结构体,表示大不改变状态。

所以下面的 getter 是非法的:

// This will get you a compiler error
readonly get { _z = 7d; return _z; }

此处声明:https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/readonly

In an instance member declaration within a structure type, readonly indicates that an instance member doesn't modify the state of the structure.

readonly get 语法是 new addition to C# 8。它表示 getter 不能修改实例成员。

常规getters 可以修改实例:

public double X
{
    get { _x = 1; return _x; }
}

该代码完全有效;更有用的是,getter 可以更新缓存值。 readonly get 访问器不能这样做,编译器将强制执行此不变式。