程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> .NET網頁編程 >> C# >> C#入門知識 >> Usage of readonly and const

Usage of readonly and const

編輯:C#入門知識

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.

      eg: 

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

  

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved