现在的位置: 首页 > 综合 > 正文

只读字段的写入

2018年10月20日 ⁄ 综合 ⁄ 共 558字 ⁄ 字号 评论关闭

namespace TypeDemo
{
    class Program
    {
        static void Main(string[] args)
        {
            SomeType someType = new SomeType("test");
            someType.DoSomething();

        }
    }

    public sealed class SomeType
    {
        // 一个只读实例字段
        public readonly string Pathname = "Untitles";

        public SomeType(String pathName)
        {
            // 可以修改 因为代码位于构造器中,所以可行
            this.Pathname = pathName;
        }

        public String DoSomething()
        {
            //this.Pathname = "China"; //Error 无法对只读字段赋值
            Console.WriteLine(Pathname);
            return Pathname;
        }
    }
}

抱歉!评论已关闭.