C# Foundation---keyword: const & readonly & static readonly

 1 using  System;
 2 using  System.Collections.Generic;
 3 using  System.Text;
 4 using  System.Threading;
 5
 6 namespace  CSharpFoundationStudy
 7 {
 8    /**//*
 9     * const与readonly, static readonly的区别
10     * const修饰符定义常量,在定义常量时必须指定初始值,而且不能更改
11     * readonly修饰符用于"只读域",可以在动态运行时指定,但指定后也不能改变
12     * static readonly 只能在声明时初始化或者静态构造函数中初始化
13     * const或者static readonly修饰的常量是属于类级别的;而readonly修饰的,无论是直接通过赋值来初始化或者在实例构造函数里初始化,都属于实例对象级别
14     * 
15     * 详细内容参见: C#学习simply-zhao\readonly vs const.doc
16     */

17    public class ConstReadOnly
18    {
19        const string Constant = "Constant, Can't be changed";
20        public readonly string ReadOnly;
21        static readonly string SReadOnly = "Static ReadOnly";
22
23        //静态构造函数
24        static ConstReadOnly()
25        {
26            //ConstReadOnly.Constant = "Change Constant Failed"; //Error 常量不能更改
27            ConstReadOnly.SReadOnly = "Change Static ReadOnly in Static Constructor Successfully";
28        }

29
30        public ConstReadOnly()
31        {
32            ReadOnly = DateTime.Now.ToString();
33        }

34
35        public override string ToString()
36        {
37            return ConstReadOnly.Constant + "\n" + this.ReadOnly + "\n" + ConstReadOnly.SReadOnly + "\n";
38        }

39
40        //public static void Main()
41        //{
42        //    ConstReadOnly instance1 = new ConstReadOnly();
43        //    Console.WriteLine(instance1);
44        //    Thread.Sleep(2000);
45        //    ConstReadOnly instance2 = new ConstReadOnly();
46        //    Console.WriteLine(instance2);
47        //    Console.ReadLine();
48        //}
49    }

50}

51

转载于:https://www.cnblogs.com/simply-zhao/archive/2008/01/20/1046285.html

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值