3月5日 字段和属性

Profile Picture
- Published on Mar 5, 2020🌏 Public

字段和属性

字段是卸载class内的,与类型相关的变量。字段采用骆驼命名法。

    class Cat
    {
        //变量采用骆驼命名法
        //属性、方法都是首字母大写

        //包含毛色、性别、名字、饱食度四个字段
        string color, sex, name;
        int satiationDegree=50;
    }

属性是对于字段的封装。提供对字段数据的读写方法。属性命名一般都是采用首字母大写的方式。

 class Program
    {
        static void Main(string[] args)
        {
            Cat cat = new Cat();
            cat.Color = "xxx";
            Console.WriteLine(cat.Color);
        }
    }

    class Cat
    {
        string color;
        /// <summary>
        /// 对color字段进行封装,形成Color属性
        /// </summary>
        public  string Color
        {
            set {
                //设置时执行
                color = value; //set访问器中的value表示赋值进来的值
            }
            get {
                //取值时执行
                return color;
            }
        }
    }

封装的作用

控制属性的读写访问性

如果删除set访问器,会提示该属性是只读的。

如果删除get访问器,会提示该属性缺少get访问器。

验证和处理数据

  class Program
    {
        static void Main(string[] args)
        {
            Cat cat = new Cat();
            cat.Age = 30;
            cat.Age = 20;
            Console.WriteLine(cat.Age);
        }
    }

    class Cat
    {
        int age;

        public int Age
        {
            set
            {
                if (value > 20||value<0)
                {
                    Console.WriteLine("数据异常");
                }
                else
                {
                    age = value;
                }
            }
            get
            {
                return age;
            }
        }
数据异常
20

简写

        public string Sex
        {
            get;
            set;
        }

编译器在编译时会自动创建一个与属性对应的私有字段,并且实现get和set访问器。等效于下面的代码:

        string set;
        public string Set
        {
            get
            {
                return name;
            }
            set
            {
                name = value;
            }
        }

以后凡是需要给外部使用的数据,全部使用属性的形式进行书写。