一、結(jié)構(gòu)和類的區(qū)別
1、結(jié)構(gòu)的級別和類一致,寫在命名空間下面,可以定義字段、屬性、方法、構(gòu)造方法也可以通過關(guān)鍵字new創(chuàng)建對象。
2、結(jié)構(gòu)中的字段不能賦初始值。
3、無參數(shù)的構(gòu)造函數(shù)無論如何C#編譯器都會自動生成,所以不能為結(jié)構(gòu)定義一個無參構(gòu)造函數(shù)。
4、在構(gòu)造函數(shù)中,必須給結(jié)構(gòu)體的所有字段賦值。
5、在構(gòu)造函數(shù)中,為屬性賦值,不認為是對字段賦值,因為屬性不一定是去操作字段。
6、結(jié)構(gòu)是值類型,在傳遞結(jié)構(gòu)變量的時候,會將結(jié)構(gòu)對象里的每一個字段復(fù)制一份拷貝到新的結(jié)構(gòu)變量的字段中。
7、不能定義自動屬性,因為字段屬性會生成一個字段,而這個字段必須要求在構(gòu)造函數(shù)中,但我們不知道這個字段叫什么名字。
8、聲明結(jié)構(gòu)體對象,可以不使用new關(guān)鍵字,但是這個時候,結(jié)構(gòu)體對象的字段沒有初始值,因為沒有調(diào)用構(gòu)造函數(shù),構(gòu)造函數(shù)中必須為字段賦值,所以,通過new關(guān)鍵字創(chuàng)建結(jié)構(gòu)體對象,這個對象的字段就有默認值。
9、棧的訪問速度快,但空間小,堆的訪問速度慢,但空間大,當我們要表示一個輕量級的對象的時候,就定義為結(jié)構(gòu),以提高速度,根據(jù)傳至的影響來選擇,希望傳引用,則定義為類,傳拷貝,則定義為結(jié)構(gòu)。
二、Demo
        public int X
        {
            get { return x; }
            set { x = value; }
        }
        private int y;
        public int Y
        {
            get { return y; }
            set { y = value; }
        }
        public void Show()
        {
            Console.Write("X={0},Y={1}", this.X, this.Y);
        }
        public Point(int x,int y)
        {
            this.x = x;
            this.y = y;
            this.p = null;
        }
        public Point(int x)
        {
            this.x = x;
            this.y = 11;
            this.p = null;
        }
        public Point(int x, int y, Program p)
        {
            this.x = x;
            this.y = y;
            this.p = p;
        }
    }
    class Program
    {
        public string Name { get; set; }
        static void Main(string[] args)
        {
            //Point p = new Point();
            //p.X = 120;
            //p.Y = 100;
            //Point p1 = p;
            //p1.X = 190;
            //Console.WriteLine(p.X);
            //Point p;
            //p.X = 12;//不賦值就會報錯
            //Console.WriteLine(p.X);
            //Point p1 = new Point();
            //Console.WriteLine(p1.X);//此處不賦值不會報錯,原因見區(qū)別8
            Program p = new Program() { Name="小花"};
            Point point1 = new Point(10, 10, p);
            Point point2 = point1;
            point2.p.Name = "小明";
            Console.WriteLine(point1.p.Name);//結(jié)果為小明,分析見下圖
        }
    }
新聞熱點
疑難解答
圖片精選