C# 关键字const和readonly对比
C# 关键字const和readonly对比
二者区别
- const关键字修饰的字段只能在声明的时候初始。readonly关键字修饰的字段可以在声明的时候初始化,也可以在构造器中初始化。
- const修饰的字段值在编译时确定,readonly修饰的字段值在运行时确定。
public static readonly uint timeStamp = (uint)DateTime.Now.Ticks;
readonly字段赋值的场合
- 当变量声明时
public readonly int y = 5;
该字段为实例字段时,在包含readonly字段声明的类的实例构造器中;或者,该字段为静态字段时,在包含readonly字段声明的静态构造器中。这是能把readonly字段作为out和ref参数传递的唯一情况。
在构造其中赋值。
using System;
namespace readonly关键字
{
internal class Program
{
private static void Main()
{
var myClass = new MyClass();
Console.WriteLine("number1 = {0} , number2 = {1} , number3 = {2} , number4 = {3} , number5 = {4}",
myClass.Number1, myClass.Number2, MyClass.Number3, myClass.Number4, myClass.Number5);
Console.ReadKey();
}
}
internal class MyClass
{
public readonly int Number1 = 100;//在声明时赋值
public readonly int Number2;
public static readonly int Number3;
public readonly int Number4 = 400;
public readonly int Number5 = 500;
static MyClass()
{
Number3 = 300;
}
public MyClass()
{
Number2 = 200;//在构造器中赋值
ChangeValue(out Number4,ref Number5);
ChangeValue1(Number4, Number5);//值没有改变
}
public void ChangeValue(out int p1, ref int p2)
{
p1 = 401;
p2 = 501;
}
public void ChangeValue1(int p1,int p2)
{
p1 = 402;
p2 = 502;
}
}
}