1using System;
 2using System.Collections.Generic;
 3using System.Text;
 4using System.Threading;
 5
 6namespace 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
posted on 2008-01-20 15:37  simply-zhao  阅读(151)  评论(0)    收藏  举报