Usage of readonly and const_.NET_编程开发_程序员俱乐部

中国优秀的程序员网站程序员频道CXYCLUB技术地图
热搜:
更多>>
 
您所在的位置: 程序员俱乐部 > 编程开发 > .NET > Usage of readonly and const

Usage of readonly and const

 2014/6/21 16:53:20  istone  程序员俱乐部  我要评论(0)
  • 摘要:Manynewlearnerscannotmakesuretheusagescenariosofreadonlyandconstkeywords.Inmyopinion,themainreasonofusingreadonlykeywordistheefficiency.butinmostoccasions,efficiencyisn’ttreatedasthehighlevel.soI’mwillingtousereadonlykeyword
  • 标签:Usage

Many new learners can not make sure the usage scenarios of readonly and const keywords. In my opinion, the main reason of using readonly keyword is the efficiency. but in most occasions, efficiency isn’t treated as the high level. so I’m willing to use readonly keyword. because of it’s much more flexibility. The nature differences of these two keywords are as below:

one: const is a compile-time constant, but readonly is a runtime constant.

two: const can only modify the primitive types, enum types and string types, but readonly has no limits.

For the first point, because of the compile-time constant feature, so natively it’s static and you can’t add the static modifier manually.

       eg: static const int value = 100;

For the efficiency of const keyword, after compiled by the compiler, the constants where they are used will be replaced by it’s real value.

For the readonly variable , it’s assigned when in runtime, then it’s value can not be changed.

The so-called can not be changed contains two meanings.

  1. For value type variable, it’s value can not be changed.
  2. For reference type variable, it’s reference can not be changed, but the value of it’s referenced instance can be changed.

      eg: 

class="brush:csharp;gutter:true;">class Istone
{

  public readonly int age;

  public Istone(int age)
  {

        this.age = age;
   }
}

Istone istone = new Istone(20);

istone.age = 300;         //it’s wrong, can’t assign value again for readonly variable

  

For the reference variable, after giving an example, you will rapidly understand.

   eg:

 class  Istone2
{
  public readonly Student stu;

  public Istone2(Student stu)

  {
     this.stu = stu;
  }
}

Istone2 stu2 = new Istone2(new Student(){age= 10});

stu2.stu = new Student(){age = 20};//wrong

  

Can not assign value to readonly field, but can change it’s referenced instance like below:

       stu2.stu.age = 20;

PS: readonly variable can be initialized, and then assigned value one or more time in the constructor.

 

发表评论
用户名: 匿名