get与set的练习

来源:互联网 发布:c语言怎么导入函数库 编辑:程序博客网 时间:2024/06/06 13:25
using System;using System.Collections.Generic;using System.Linq;using System.Text;namespace 类的练习2_get与set{    class Program    {        static void Main(string[] args)        {            Person my = new Person();            my.Age = 20;            Console.WriteLine("我的年龄是{0}", my.Age);//20            my.Age = -100;            Console.WriteLine("我的年龄是{0}",my.Age);//20            my.Age1 = -1;            Console.WriteLine("我的年龄是{0}", my.Age1);//-1            Person2 p = new Person2();            p.Age = 30;            p.Age = p.Age + 10;            Console.WriteLine("我的年龄是{0}", p.Age);//3            Console.ReadKey();        }    }    class Person     {        private int age;        public int Age1;        public int Age //Age未保存数据,都保存到age中了        {            set//赋值,只写            {                if (value < 0)//public字段和属性的区别,可以进行非法字段值的判断                {                    return;                }                this.age=value;            }             get //取值,只读            {                return this.age;            }        }    }    class Person2     {        private int age;        public int Age         {            set             {                this.age = value;            }            get             {                return 3;            }        }    }}
原创粉丝点击