c# - D 中 C# `readonly` 关键字的等价物?

标签 c# immutability d

根据我在阅读 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/

相关文章:

performance - D 中异常处理的开销

dlang : relocation R_X86_64_32 against `.rodata' can not be used when making a shared object; recompile with -fPIC

c# - ViewDataFactory 和强类型母版页

c# - 锁定字典上的 Dictionary Add() 异常

c# - 在 WCF 回调中收到的消息乱序

java - 可变性和 Spring

callback - D:委托(delegate)还是回调?

c# - 解析值行 1,位置 1 时遇到意外字符

python - python中的不可变对象(immutable对象)

c# - 如何为复杂的,不变的模型实现真实的单一来源?