【发布时间】:2018-07-31 04:42:52
【问题描述】:
这是声明不可变结构的正确方法吗?
public struct Pair
{
public readonly int x;
public readonly int y;
// Constructor and stuff
}
我想不出为什么会遇到问题,但我只是想问一下。
在这个例子中,我使用了整数。如果我改用一个类,但该类也是不可变的,像这样呢?这也应该可以正常工作,对吧?
public struct Pair
{
public readonly (immutableClass) x;
public readonly (immutableClass) y;
// Constructor and stuff
}
(顺便说一句:我知道使用 Properties 更通用并且允许更改,但是这个结构实际上是为了存储两个值。我只是对这里的不变性问题感兴趣。)
【问题讨论】:
-
readonlyproperties/members 只能在构造函数中设置(最迟)。它们不能使用属性初始化语法来设置。 -
readonly仅影响赋值运算符。它没有 C++ 的const关键字那么强的语义。
标签: c# struct immutability