c# 常量(const) 和 只读属性(readonly)

2021/4/17 1:25:10

本文主要是介绍c# 常量(const) 和 只读属性(readonly),对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

namespace ConsoleApp1
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine(Web.WebsiteURL);

            Web web = new Web();
            Console.WriteLine(web.version);
        }
    }

    class Web
    {
    	// 常量
        public const string WebsiteURL = "http://www.baidu.com";
        // 只读字段
        public readonly string version = "1.0.0";
    }
}
  • 常量隶属于类,而不是对象,即没有"实例常量"
  • "实例常量"的角色由只读实例字段担当

各种只读的应用常见

  • 为了提高程序可读性和执行效率 ==> 常量
  • 为了防止对象的值被改变 ==> 只读字段
  • 向外暴露不允许修改的数据 ==> 只读属性(静态或非静态), 功能与常量有一些重叠
  • 当希望成为常量的值其类型不能被常量声明接收时(类/自定义结构体) ==> 静态只读字段 (这句话太绕了)
   class Web
    {
        public const string WebsiteURL = "http://www.baidu.com";
        public readonly string version = "1.0.0";

        // 错误,因为常量只能接收基本类型数据
        //public const Building Location = new Building("gz");

        // 正确
        public static readonly Building Location = new Building("gz");
    }

    class Building
    {

        public string Address { get; set; }

        public Building(string address)
        {
            this.Address = address;
        }
    }


这篇关于c# 常量(const) 和 只读属性(readonly)的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!


扫一扫关注最新编程教程