c#中关键字readonly、const

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

可以使用如下方法赋值:

ContractedBlock.gif ExpandedBlockStart.gif 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);
}
}

不能使用如下方法赋值:

ContractedBlock.gif ExpandedBlockStart.gif 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 字段可用于运行时常量。

转载于:https://www.cnblogs.com/zengen/archive/2011/03/29/1998528.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值