我有一个问题。最近我发现自己使用了 3 行不同的代码,仔细检查它们看起来和感觉都一样。
public static class constant
{
public static readonly int val1 = 5;
public const int val2 = 5;
public static int val3 { get { return 5; } }
}
我的问题是,它们是一样的吗?应该用一个代替另一个吗?如果是这样。什么时候?
在 visual studio 中还有一个额外的问题,为什么它们在 intellisense 中的表示方式不同?
声明为只读的成员提供了在类的(静态)构造函数中更改的可能性,而 const 成员不能在运行时更改。
将字段声明为 const 使其自动静态,引用 §10.3.7:
When a field, method, property, event, operator, or constructor
declaration includes a static modifier, it declares a static member.
In addition, a constant or type declaration implicitly declares a
static member.
第三个只是一个只读属性,恰好总是返回 5。
您永远不应该使用这样的属性,并尽可能使用 const 成员,以允许编译器和/或抖动执行它们的优化并帮助其他人阅读您的代码(该属性对我来说是一种 WTF) .如果需要在程序启动期间初始化的常量值(例如,机器的核心数),则必须使用静态只读成员。
这是 C# 规范 (§10.5.2.1) 中的一个很好的例子:
A static readonly field is useful when a symbolic name for a constant
value is desired, but when the type of the value is not permitted in a
const declaration, or when the value cannot be computed at
compile-time. In the example
public class Color
{
public static readonly Color Black = new Color(0, 0, 0);
public static readonly Color White = new Color(255, 255, 255);
public static readonly Color Red = new Color(255, 0, 0);
public static readonly Color Green = new Color(0, 255, 0);
public static readonly Color Blue = new Color(0, 0, 255);
private byte red, green, blue;
public Color(byte r, byte g, byte b) {
red = r;
green = g;
blue = b;
}
}
the Black, White, Red, Green, and Blue members cannot be declared as
const members because their values cannot be computed at compile-time.
However, declaring them static readonly instead has much the same
effect.
还有另一个区别(§10.5.2.2):
Constants and readonly fields have different binary versioning
semantics. When an expression references a constant, the value of the
constant is obtained at compile-time, but when an expression
references a readonly field, the value of the field is not obtained
until run-time.
因此,总而言之,即使乍一看它们可能看起来很相似,它们也有很大的不同,您应该使用最适合您意图的那个。