ASP.NET中readonly與const的區別詳解_實用技巧

來源:互聯網
上載者:User

const是一個修飾常量的關鍵字,它限定一個變數不允許被改變。使用const在一定程度上可以提高程式的安全性和可靠性,它在程式設計中有著非常重要的作用,給開發人員帶來非常方便的應用。
下面我們來建一個控制台應用程式作測試

public class Test{  public readonly string name = "George";  public const string coname = "ABC Company LLC";  public Test(string name)  {    // readonly 修飾的變數能且只能在 Constructor(建構函式)中被改變      this.name = name;  }  public string _name  {    get    {      return name;    }    //不可以對readonly修飾的變數進行Set操作      //set        //{        //  name = value;     //}     }}  class Program{  static void Main(string[] args)  {    Test obj = new Test("Test");    //readonly的變數不可以修改值,只能在 Constructor(建構函式)中被改變        //obj.name = "New Value";         Console.WriteLine(obj.name);       //const 的變數直接通過對象訪問,不需要執行個體化     Console.WriteLine(Test.coname);    Console.Read();  }}

以前一直以為 readonly 與 const 的作用是一樣的,現在明白它們之間的區別了,不知道您是否也明白了呢?希望大家有所收穫吧!

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.