Const 和 readonly

const 关键字用于修改字段或局部变量的声明。 它指定字段或局部变量的值是常数,不能被修改。

例如:

public const double gravitationalConstant = 6.673e-11;

只有 C# 内置类型(System.Object 除外)可以声明为 const 下表列出了C# 内置类型:

bool

System.Boolean

byte

System.Byte

sbyte

System.SByte

char

System.Char

decimal

System.Decimal

double

System.Double

float

System.Single

int

System.Int32

uint

System.UInt32

long

System.Int64

ulong

System.UInt64

object

System.Object

short

System.Int16

ushort

System.UInt16

string

System.String

 

用户定义的类型(包括类、结构和数组)不能为 const 请使用 readonly 修饰符创建在运行时初始化一次即不可再更改的类、结构或数组。

对于引用类型的常量,除string外,其他的值只能是null

如下:

class Test

{

// below wrong.

public const Test2 T2 = new Test2();

// below right, can only be initialized with null for reference type except string.

这种写法虽然编译通过,但其实没有任何意义了,所以说对类不声明为const.

public const Test2 T3 = null;

}

 

class Test2

{

}

将产生编译错误:

A const field of a reference type other than string can only be initialized

with null.

 

虽然 const 字段是编译时常量,但 readonly 字段可用于运行时常量,如此行所示:public static readonly uint l1 = (uint)DateTime.Now.Ticks;

 

const常量通过类名访问,不允许在常数声明中使用 static 修饰符。

 

Difference between static readonly and const:

The difference is that the value of a static readonly field is set at run time, and can thus be modified by the containing class, whereas the value of a const field is set to a compile time constant.

In the static readonly case, the containing class is allowed to modify it only

  • in the variable declaration (through a variable initializer)
  • in the static constructor (instance constructors, if it's not static)

static readonly is typically used if the type of the field is not allowed in a const declaration, or when the value is not known at compile time.

Instance readonly fields are also allowed. 

Remember that for reference types, in both cases (static and instance) the readonly modifier only prevents you from assigning a new reference to the field.  It specifically does not make immutable the object pointed to by the reference.

这里说的是对于引用类型,readonly只是保证你不能给它赋新的引用,但是它所指向的值是可以改变的。

 

class Program
{
static void Main(string[] args)
{
var t
= new MyClass();
t.Add();
}
}

public class MyClass
{
private readonly Collection<string> _str = new Collection<string>();
public MyClass()
{
_str.Add(
"a");
_str.Add(
"b");
_str.Add(
"c");
}

public void Add()
{
_str.Add(
"d");
foreach (var s in _str)
Debug.WriteLine(s);
}
}

 这样添加是成功的,最后输出:

a

b

c

d

posted on 2011-08-24 17:27 cutebear 阅读( ...) 评论( ...) 编辑 收藏

转载于:https://www.cnblogs.com/bear831204/archive/2011/08/24/2152291.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值