C#readonly关键字

readonly是一种常量修饰符,区别于const,分别进行记录。

先说const,const是静态常量或者叫编译时常量,是指编译器在编译时候会对常量进行解析,并将常量的值替换成初始化的那个值。必须在声明的时候初使化, const 关键字声明的字段默认带有 static 属性,因此只可以通过类对 const 常量进行访问。

 class Person
  	{
       public const int age = 10;
    }
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine(Person.age);
        }
    }

readonly称为动态常量,也叫运行时常量,运行时常量的值是在运行的那一刻才获得的,编译器编译期间将其标示为只读常量,而不用常量的值代替,这样动态常量不必在声明的时候就初始化(当然也可以在声明的时候初使化),而可以延迟到构造函数中初始化。

 public class Person{
       public readonly int age ;
       public Person (){
           age = 10;
       }
    }  
    class Program
    {
        static void Main(string[] args)
        {
            Person a = new Person();
            Console.WriteLine(a.age);
        }
    }

const 与 static readonly 基本相似,但是在初始化方面,static readonly 还可以通过静态构造函数进行赋值。const 在程序编译期间获取字段的值,而 static readonly 是在程序运行时获取字段的值。

public class Person{
       public static readonly int age=10 ;
       public Person (){
          // age = 10;
       }
    }  
    class Program
    {
        static void Main(string[] args)
        {
            Person a = new Person();
            Console.WriteLine(Person.age);
        }
    }
  • 12
    点赞
  • 21
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值