美文网首页
用属性 (Property) 来代替可访问的数据成员

用属性 (Property) 来代替可访问的数据成员

作者: Pomelo的笔记本 | 来源:发表于2017-10-02 20:37 被阅读0次
class Student
    {
        private string code = "N.A";
        private string name = "not known";
        private int age = 0;

        // 声明类型为 string 的 Code 属性
        public string Code
        {
            get
            {
                return code;
            }
            set
            {
                code = value;
            }
        }

        // 声明类型为 string 的 Name 属性
        public string Name
        {
            get
            {
                return name;
            }
            set
            {
                name = value;
            }
        }

        // 声明类型为 int 的 Age 属性
        public int Age
        {
            
            get
            {
                return age;
            }
            set
            {
                age = value;
            }
        }
        //自定义类重载ToString方法,便于调试
        public override string ToString()
        {
            return "Code = " + Code + ", Name = " + Name + ", Age = " + Age;
        }
    }
    class ExampleDemo
    {
        public static void Main()
        {
            // 创建一个新的 Student 对象
            Student s = new Student();

            // 设置 student 的 code、name 和 age
            s.Code = "001";
            s.Name = "Zara";
            s.Age = 9;
            Console.WriteLine("Student Info: {0}", s);
            // 增加年龄
            s.Age += 1;
            Console.WriteLine("Student Info: {0}", s);
            Console.ReadKey();
        }
    }

相关文章

网友评论

      本文标题:用属性 (Property) 来代替可访问的数据成员

      本文链接:https://www.haomeiwen.com/subject/xdityxtx.html