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)的常量。
【推荐】还在用 ECharts 开发大屏?试试这款永久免费的开源 BI 工具!
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步