C#----Get和Set在属性中的使用

来源:互联网 发布:k速电子狗升级软件 编辑:程序博客网 时间:2024/05/01 19:19

Get和Set在属性中的作用:

第一个作用:保证数据的安全性,对字段进行了有效的保护。

第二个作用:起到监视作用

private int width=0;public int Width{    get{return width;}    set{width=value*2;}}可以监视字段的变化,在Set中使用private int width=0;public int Width{    get{return width;}    set    {        //Do something        width=value;    }}        private int width = 1;        public int Width        {            get { return width*2; }            set {                Console.WriteLine("变化前:{0}", width); //1                width = value + 2;                Console.WriteLine("变化后:{0}", width); //7=5+2            }        }        static void Main(string[] args)        {            Program p = new Program();            Console.WriteLine(p.Width);            p.Width = 5;//这里width的值不会是5的            Console.WriteLine(p.Width);//14=2*7            Console.WriteLine(p.Width);//14            Console.Read();        }


0 0
原创粉丝点击