what’s the differences between readonly & const in C# 在C#中readonly和const的區別

來源:互聯網
上載者:User
1. the similar feature 相似性
   grammar:
    public const int x=100;
    public readonly int x;    
    const variable and readonly variable can not be modified once they are initialized in run-time. However,the main differences between them is the time to be initialized!
const變數和readonly變數的值一旦被初始化其值在運行時就不能再改變。但是,他們之間的區別在於他們被初始化的時機是不一樣的。

2 the differences
    const variable must be initialized when it's be declared, because  its value is set in compile-time before the respective object is constructed. However, readonly can be initialized dynamically. that is to say, its value can be set via class constructor or vairable initiazer(no other feasible ways).
    const常量必須在其聲明時被初始化,因為其值在編譯而相應物件建構之前就被設定。但是 ,readonly可以被動態設定,其既可以在初始化時設定,也可以在建構函式中設定(其他方式均不可)。
   e.g
    public class A
    {
        public const m_x=100;

        //public const m_x=DataTime.Now.Tricks;
        //error!DataTime.Now.Tricks can not give a exact value for const variable in compile-time.
        public readonly long  m_y=DataTime.Now.Tricks;
        //it can be initialized via viriable initiazer

        public readonly int  m_z;
        public A()
        {
        m_z=DataTime.Now.Tricks;
        //it also can be initialized via constructor;
        }
    }
    

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.