1. 程式人生 > >C#----Get和Set在屬性中的使用

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