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

C#關鍵字readonly與const的異同

編輯:C#基礎知識
readonly與const

readonly與const

在C#中,readonly 與 const 都是定義常量,但不同之處在於:readonly 是運行時常量,而 const 是編譯時常量。

public const int intValue = 100;

public void Test()
{
    Console.WriteLine(intValue*100);
}

在上面的代碼中, intValue是一個int類型的常量並且用100來初始化它,即 intValue 就是100,編譯器會在編譯時用100來替換程序中的intValue。

class Test
{
    public readonly Object _readOnly; 

    public Test()
    {
        _readOnly=new Object();    //right
    }

    public void ChangeObject()
    {
        _readOnly=new Object();    //compliler error
    }
}

使用readonly將 _readOnly變量標記為只讀(常量),這裡表示的是這個變量是常量,而不是指它所指向的對象是常量(看下面的代碼)。而且它不同於const在編譯時就已經確定了綁定對象,他是在運行時根據需求動態實現的,就如上面的代碼,_readOnly就是在構造函數內被初始化的,即可以通過構造函數來為_readOnly指定不同的初始值。而一旦這個值指定的了之後在運行過程中就不能再更改。

class Person
{
    public int Age{get;set;}
}

class Test
{
    private readonly Person _readOnly;
    private readonly int _intValue;

    public Test()
    {
        _readOnly=new Person();
        _intValue=100;
    }

    public Test(int age,int value)
    {
        _readOnly=new Person(){ Age=age;}
        _intValue=value;
    }

    public void ChangeAge(int age)
    {
        _readOnly.Age=age;
    }

    public void ChangeValue(int value)
    {
        _intValue=value;    //comppiler error
    }

    public int GetAge()
    {
        return _readOnly.Age;
    }

    public int GetValue()
    {
        return _intValue;
    }
    
    public static void Main()
    {
        Test testOne=new Test();
        Test testTwo=new Test(10,10);
          
        Console.WriteLine("testOne: "+testOne.GetAge()+" "+testOne.GetValue());
        Console.WriteLine("testTwo: "+testTwo.GetAge()+" "+testTwo.GetValue());

        testOne.ChangeAge(20);
        testTwo.ChangeValue(20);
        Console.WriteLine(testOne.GetAge());
        Console.WriteLine(testTwo.GetValue());
    }
}

readonly 與 const 最大的區別在於readonly 是運行時綁定,而且可以定義對象常量,而 const 只能定義值類型(如int)的常量。

  1. 上一頁:
  2. 下一頁: