根据我在阅读 D 时的理解,当在变量上使用 immutable
关键字时,变量的值必须在编译时已知,而 C# 的 readonly
不需要,readonly
字段可以使用非静态值在类构造函数中分配。这在 D 中可能吗?
最佳答案
在 D2 中,const 成员只能在构造函数内部初始化(或直接在类声明中,但不能同时初始化):
import io = std.stdio;
class A
{
const int member;
this(int nb)
{
this.member = nb;
}
}
void main()
{
A a = new A(12);
io.writeln(a.member);
//a.member = 14; //Error: can only initialize const member member inside constructor
}
关于c# - D 中 C# `readonly` 关键字的等价物?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6036807/