const和readonly的区别
class Program1
{
public const string name = "小明";
private static readonly string age;
private static string sex;
//readonly是运行常量
private readonly string address = new string("中国广东");
//const是编译常量不能用new初始化
//private const string telphone = new string("123456");
public Program1()
{
sex = "男";
//static readonly只能声明时或静态构造函数中初始化
//age = "23";
}
public void Fun()
{
//const可以声明局部变量
const int data = 90;
//readonly不可以声明局部变量
//readonly int data1 = 80;
}
}
class Program2
{
static void Main()
{
Program1 p = new Program1();
//const字段是静态的可以通过类名访问
Console.WriteLine(Program1.name);
//const字段不能通过对象实例访问
//Console.WriteLine(p.name);
}
}