C#温故而知新学习系列之面向对象编程—11-自动属性

来源:互联网 发布:java api 编辑:程序博客网 时间:2024/05/03 09:13
       自动属性

  当属性访问器中不需要其他逻辑时,自动实现的属性可时属性的声明变得更加简洁

  创建自动属性

  一旦在类中声明了自动属性,那么编译器将创建一个私有的匿名后备字段,但是这个私有字段只能通过属性的get和set访问器进行访问

  自动属性必须同时声明get和set访问器,假如要创建只读的自动属性,必须在set访问器前加上privvate关键字

  实例

  using System;
  using System.Collections.Generic;
  using System.Linq;
  using System.Text;

  namespace _12_AutoAttribute
  {
      class Student
      {
          public int Age
          {
              get;
              set;
          }
          public bool Sex
          {
              get;
              private set;
          }
      }

      class Program
      {
          static void Main(string[] args)
          {
              Student stu = new Student();
              stu.Age = 25;
              Console.WriteLine(stu.Age.ToString());
              Console.ReadKey();
          }
      }
  }

  运行效果

  

原创粉丝点击