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

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();
        }


 

 

posted @ 2014-04-03 11:30  deeeeeed  阅读(306)  评论(0编辑  收藏  举报

pppppppppppppp