const(C# 參考)

來源:互聯網
上載者:User

C# 程式員參考 
const(C# 參考) 

const 關鍵字用於修改欄位或局部變數的聲明。它指定欄位或局部變數的值是常數,不能被修改。例如:

        const int x = 0;
public const double gravitationalConstant = 6.673e-11;
private const string productName = "Visual C#";
備忘

常數聲明的類型指定聲明引入的成員類型。常數運算式必須產生具有目標類型或者可隱式轉換為目標類型的類型的值。

常數運算式是在編譯時間可被完全計算的運算式。因此,對於參考型別的常數,可能的值只能是 string 和 null。

常數聲明可以聲明多個常數,例如:

public const double x = 1.0, y = 2.0, z = 3.0;
不允許在常數聲明中使用 static 修飾符。

常數可以參與常數運算式,如下所示:

public const int c1 = 5;
public const int c2 = c1 + 100;
注意
readonly 關鍵字與 const 關鍵字不同。const 欄位只能在該欄位的聲明中初始化。readonly 欄位可以在聲明或建構函式中初始化。因此,根據所使用的建構函式,readonly 欄位可能具有不同的值。另外,const 欄位是編譯時間常數,而 readonly 欄位可用於運行時常數,如下面的程式碼所示:public static readonly uint l1 = (uint)DateTime.Now.Ticks;
 

樣本

// const_keyword.cs
using System;
public class ConstTest
{
    class SampleClass
    {
        public int x;
        public int y;
        public const int c1 = 5;
        public const int c2 = c1 + 5;

        public SampleClass(int p1, int p2)
        {
            x = p1;
            y = p2;
        }
    }

    static void Main()
    {
        SampleClass mC = new SampleClass(11, 22);  
        Console.WriteLine("x = {0}, y = {1}", mC.x, mC.y);
        Console.WriteLine("c1 = {0}, c2 = {1}",
                          SampleClass.c1, SampleClass.c2 );
    }
}
輸出
x = 11, y = 22
c1 = 5, c2 = 10
該樣本說明如何將常數用作局部變數。

// const_keyword_2.cs
using System;
public class MainClass
{
    static void Main()
    {
        const int c = 707;
        Console.WriteLine("My local constant = {0}", c);
    }
}
輸出
My local constant = 707

聯繫我們

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