C#細節之const&readonly

來源:互聯網
上載者:User
const是常量,readonly是唯讀,“部落格園er”都知道:)
那麼他們的區別是什麼那?個人總結如下:
一、賦值
1)const修飾的變數在定義時必須賦初值,其他位置不容許改變變數值;
2)readonly修飾的變數可以在定義時賦值也可以在建構函式中賦值,其他位置不容許改變變數值。
二、調用
1)const修飾的變數需要用類名來調用如同static成員一樣。
2)readonly修飾的變數需要用對象來調用。
三、代碼
例:
public class ConstReadOnly
    {
        //public const string FirstName; //Error:const 定義變數時要初始化
        public const string LastName = "Landpy";
        public readonly string Age = “0”;
        public ConstReadOnly()
        {
            Age = "27";
        }
        public void Deal()
        {
            //Age = "123";//Error:ReadOnly只能在建構函式或定義時賦值
            //LastName = "Peter";//Error:Const只能在定義時賦值
            string Tmp = String.Empty;
            Tmp = ConstReadOnly.LastName;
            //Tmp = ConstReadOnly.Age;//Error:readonly修飾的變數只能用對象調用
            ConstReadOnly constReadOnly = new ConstReadOnly();
            //Tmp = constReadOnly.LastName;//Error:const修飾的變數只能用類名調用
            Tmp = constReadOnly.Age;
        }
    }
相關文章

聯繫我們

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