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