c#中关键字readonly、const

readonly:可以在字段上使用的修饰符,当字段声明包括 readonly 修饰符时,该声明引入的字段赋值只能作为声明的一部分出现,或者出现在同一类的构造函数中。

可以使用如下方法赋值:

View Code
// cs_readonly_keyword.cs
// Readonly fields
using System;
public class ReadOnlyTest
{
class SampleClass
{
public int x;
// Initialize a readonly field
public readonly int y = 25;
public readonly int z;

public SampleClass()
{
// Initialize a readonly instance field
z = 24;
}

public SampleClass(int p1, int p2, int p3)
{
x
= p1;
y
= p2;
z
= p3;
}
}

static void Main()
{
SampleClass p1
= new SampleClass(11, 21, 32); // OK
Console.WriteLine("p1: x={0}, y={1}, z={2}", p1.x, p1.y, p1.z);
SampleClass p2
= new SampleClass();
p2.x
= 55; // OK
Console.WriteLine("p2: x={0}, y={1}, z={2}", p2.x, p2.y, p2.z);
}
}

不能使用如下方法赋值:

View Code
class Age
{
readonly int _year;
Age(
int year)
{
_year
= year;
}
void ChangeYear()
{
_year
= 1967; // Will not compile.
}
}

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

Note注意

readonly 关键字与 const 关键字不同:

1. const 字段只能在该字段的声明中初始化;readonly 字段可以在声明或构造函数中初始化;因此,根据所使用的构造函数,readonly 字段可能具有不同的值。

2. const 字段是编译时常量,而 readonly 字段可用于运行时常量。

posted @ 2011-03-29 10:52  [曾恩]  阅读(323)  评论(0编辑  收藏  举报