在C#中常量和只读之间有什么区别?
你什么时候会用一个代替另一个?
在C#中常量和只读之间有什么区别?
你什么时候会用一个代替另一个?
当前回答
只读:可以在运行时通过Ctor更改值。但不通过成员函数
常量:默认情况下为静态。值不能从任何位置更改(Ctor、Function、runtime等no where)
其他回答
它们都是常量,但在编译时也可以使用常量。这意味着差异的一个方面是,可以使用常量变量作为属性构造函数的输入,但不能使用只读变量。
例子:
public static class Text {
public const string ConstDescription = "This can be used.";
public readonly static string ReadonlyDescription = "Cannot be used.";
}
public class Foo
{
[Description(Text.ConstDescription)]
public int BarThatBuilds {
{ get; set; }
}
[Description(Text.ReadOnlyDescription)]
public int BarThatDoesNotBuild {
{ get; set; }
}
}
我相信常量值对于所有对象都是相同的(并且必须用文字表达式初始化),而只读对于每个实例化可以是不同的。。。
这说明了这一点。概要:const必须在声明时初始化,readonly可以在构造函数上初始化(因此,根据使用的构造函数,其值不同)。
编辑:关于细微的差异,请参见上面吉树的gotcha
const是编译时常量,而readonly允许在运行时计算值并在构造函数或字段初始值设定项中设置。因此,“const”总是常量,但“readonly”在赋值后是只读的。
C#团队的埃里克·里佩尔(Eric Lippert)有更多关于不同类型不变性的信息。
有一个只读的小陷阱。只读字段可以在构造函数中设置多次。即使在两个不同的链式构造函数中设置了该值,它仍然是允许的。
public class Sample {
private readonly string ro;
public Sample() {
ro = "set";
}
public Sample(string value) : this() {
ro = value; // this works even though it was set in the no-arg ctor
}
}