readonly

Readonly

Readonly可修饰字段,表示此字段只能在定义处或构造器修改值,

来看DEMO

class Test

    {

        public readonly int i = 3;

        public Test()

        {

            i = 4;

        }

       

        public void OtherMethod()

        {

            //i = 5;//error messages->错误     1    无法对只读的字段赋值(构造函数或变量初始值指定项中除外)

 

        }

    }

二,需要注意的是,可以采用反射(reflection)来修改readonly字段,当某个字段是引用类型,并且该字段标记为readonly时,它就是不可改变的引用,而不是字段所引用的对象。以下代码对此进行了演示:

class Test2

    {

        public static readonly Char[] InvalidChars = new Char[] { 'A', 'B', 'C' };

 

        //public static readonly string[] InvalidStrings = new string[] { "A", "B", "C" };

       

        public static readonly int b = 1;

 

        static Test2()

        {

           

            b = 2;

        }

 

        public int getIntValue()

        {

            return b;

 

        }

}

 

 

 

class Program

{

 

        static void Main (string[] args)

        {

            //下面三行代码是合法的,可以通过编译,并可以成功修改InvalidChars数组

 

            //中的字符

 

            Test2.InvalidChars[0] = 'X';

 

            //Test2.InvalidStrings[0] = "wmj";//string[]类型

 

            //此方式,没有在构造函数中修改

            //Test2.b = 3;//error message->错误    1    无法对静态只读字段赋值(静态构造函数或变量初始值设定项中除外)

 

            //此方式,通过构造函数(static的)修改

            Test2 t2 = new Test2();

            Console.WriteLine(t2.getIntValue());

            Console.ReadLine();

 

 

            //下一行代码是非法的,无法通过编译,因为InvalidChars的引用无法更改

 

            //Test2.InvalidChars = new Char[] { 'X', 'Y', 'Z' };//error message->错误    1    无法对静态只读字段赋值(静态构造函数或变量初始值设定项中除外)

 

 

 

        }

}

F5,输出结果为2OK

 
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值