C#基础-第7章:常量和字段


常量和字段
7.1 本章内容:

  1. · 常量
  2. · 字段
using System;

namespace V1
{
    public sealed class SomeLibraryType//P(155)
    {
        // 注意:c#允许为常量指定static关键字,因为常量总是隐式为static
        public const Int32 MaxEntriesInList = 50;
    }

    public sealed class Program //P(156)
    {
        static void Main()
        {
            //调用常量
            Console.WriteLine("Max entries supported in list: "
               + SomeLibraryType.MaxEntriesInList);
        }
    }
}



namespace V2
{
    // readonly 关键字用法
    public sealed class SomeLibraryType //P(157)
    {
        // 字段和类型关联必须使用static关键字
        public static readonly Int32 MaxEntriesInList = 50;
    }

    public sealed class Program
    {
        static void Main2() //这里应该是Main
        {
            Console.WriteLine("Max entries supported in list: "
                + SomeLibraryType.MaxEntriesInList);
        }
    }

}

public sealed class SomeType //P158
{
    // 这是一个静态的readonly字段;在运行时对这个类进行初始化时,
    // 它的值会被计算并存储到内存中
    public static readonly Random s_random = new Random();

    //这是一个静态read/writer字段.
    private static Int32 s_numberOfWrites = 0;

    // 这是一个实例readonly字段
    public readonly String Pathname = "Untitled";

    // 这是一实例read/writer字段
    private System.IO.FileStream m_fs;

    public SomeType(String pathname)
    {
        //该行修改只读字段pathname
        //在构造器中可以这样做,也只能在构造器中初始化 readonly字段
        this.Pathname = pathname;
    }

    public String DoSomething()
    {
        //该行读写静态 read/writer 字段
        s_numberOfWrites = s_numberOfWrites + 1;

        // 该行读取readonly实例字段
        //this.Pathname = "test" 这样会报错
        return Pathname;
    }
}

// 重要提示:P(159)
//当某个字读是引用类型,并且该字段标记为readonly时,不可改变的是引用,而非字段引用的对象,以下代码对此进行了演示:
internal static class ReadOnlyReferences
{
    public sealed class AType
    {
        // InvalidChars 总是引用同一个数组对象
        public static readonly Char[] InvalidChars = new Char[] { 'A', 'B', 'C' };
    }

    public sealed class AnotherType
    {
        public static void M()
        {
            //下面三行代码是合法的,可以通过编译,并可以成功
            AType.InvalidChars[0] = 'X';
            AType.InvalidChars[1] = 'Y';
            AType.InvalidChars[2] = 'Z';

            // 下面代码是非法的,无法通过编译,因为不能InvalidChars引用别的什么东西
            //AType.InvalidChars = new Char[] { 'X', 'Y', 'Z' };
        }
    }
}

猜你喜欢

转载自www.cnblogs.com/eric-yuan/p/10231595.html