gpt4 book ai didi

c# - 常量与只读

转载 作者:太空狗 更新时间:2023-10-29 18:08:35 26 4
gpt4 key购买 nike

今天我发现一篇文章,其中const 字段称为编译时常量,而readonly 字段称为运行时常量。这两句出自《Effective C#》。我在 MSDN 和语言规范中进行了搜索,没有找到任何有关运行时常量的内容。

没有冒犯,但我认为运行时常量不是一个恰当的短语。

private readonly string foo = "bar";

创建一个名为“foo”的变量,其值为“bar”,值为只读,这里是一个变量,与constant无关。只读变量仍然是一个变量,它不能是一个常量。变量和常量是互斥的。

也许这个问题有些过分了,还是想听听大家的意见。你怎么看?

最佳答案

我认为作者的意思如下:

考虑示例:

public class A {

public const int a = Compute();

private static int Compute(){

/*some computation and return*/
return some_computed_value;
}
}

这个,不会编译,因为你必须有常量值才能分配给 a 。所以这是编译时常量的意思。

相反,如果您将其更改为

public class A {

public readonly int a = Compute();

private static int Compute(){
/*some computation and return*/
return some_computed_value;
}
}

编译。它在运行时 进行计算并将其分配给a。这是运行时常量

的意思

关于c# - 常量与只读,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11323617/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com