readonly與const函數
在C#中,readonly 與 const 都是定義常量,但不一樣之處在於:readonly 是運行時常量,而 const 是編譯時常量。spa
public const int intValue = 100; public void Test() { Console.WriteLine(intValue*100); }
在上面的代碼中, intValue是一個int類型的常量而且用100來初始化它,即 intValue 就是100,編譯器會在編譯時用100來替換程序中的intValue。code
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)的常量。blog