readonly与const

王朝学院·作者佚名  2016-08-28
窄屏简体版  字體: 小  |  中  |  大  |  超大  

readonly与const

在C#中,readonly 与 const 都是定义常量,但不同之处在于:readonly 是运行时常量,而 const 是编译时常量。

publicconstintintValue =100;publicvoidTest()

{

Console.WriteLine(intValue*100);

}

在上面的代码中, intValue是一个int类型的常量并且用100来初始化它,即 intValue 就是100,编译器会在编译时用100来替换程序中的intValue。

classTest

{publicreadonlyObject _readOnly;publicTest()

{

_readOnly=newObject();//right}publicvoidChangeObject()

{

_readOnly=newObject();//compliler error}

}

使用readonly将 _readOnly变量标记为只读(常量),这里表示的是这个变量是常量,而不是指它所指向的对象是常量(看下面的代码)。而且它不同于const在编译时就已经确定了绑定对象,他是在运行时根据需求动态实现的,就如上面的代码,_readOnly就是在构造函数内被初始化的,即可以通过构造函数来为_readOnly指定不同的初始值。而一旦这个值指定的了之后在运行过程中就不能再更改。

classPerson

{publicintAge{get;set;}

}classTest

{PRivatereadonlyPerson _readOnly;privatereadonlyint_intValue;publicTest()

{

_readOnly=newPerson();

_intValue=100;

}publicTest(intage,intvalue)

{

_readOnly=newPerson(){ Age=age;}

_intValue=value;

}publicvoidChangeAge(intage)

{

_readOnly.Age=age;

}publicvoidChangeValue(intvalue)

{

_intValue=value;//comppiler error}publicintGetAge()

{return_readOnly.Age;

}publicintGetValue()

{return_intValue;

}publicstaticvoidMain()

{

Test testOne=newTest();

Test testTwo=newTest(10,10);

Console.WriteLine("testOne:"+testOne.GetAge()+""+testOne.GetValue());

Console.WriteLine("testTwo:"+testTwo.GetAge()+""+testTwo.GetValue());

testOne.ChangeAge(20);

testTwo.ChangeValue(20);

Console.WriteLine(testOne.GetAge());

Console.WriteLine(testTwo.GetValue());

}

}

readonly 与 const 最大的区别在于readonly 是运行时绑定,而且可以定义对象常量,而 const 只能定义值类型(如int)的常量。

 
 
免责声明:本文为网络用户发布,其观点仅代表作者个人观点,与本站无关,本站仅提供信息存储服务。文中陈述内容未经本站证实,其真实性、完整性、及时性本站不作任何保证或承诺,请读者仅作参考,并请自行核实相关内容。
 
© 2005- 王朝網路 版權所有 導航