詳說C#中的結構struct


https://www.cnblogs.com/jhlxyp/articles/4322964.html

 

一、結構和類的區別

1、結構的級別和類一致,寫在命名空間下面,可以定義字段、屬性、方法、構造方法也可以通過關鍵字new創建對象。

2、結構中的字段不能賦初始值。

3、無參數的構造函數無論如何C#編譯器都會自動生成,所以不能為結構定義一個無參構造函數。

4、在構造函數中,必須給結構體的所有字段賦值。

5、在構造函數中,為屬性賦值,不認為是對字段賦值,因為屬性不一定是去操作字段。

6、結構是值類型,在傳遞結構變量的時候,會將結構對象里的每一個字段復制一份拷貝到新的結構變量的字段中。

7、不能定義自動屬性,因為字段屬性會生成一個字段,而這個字段必須要求在構造函數中,但我們不知道這個字段叫什么名字。

8、聲明結構體對象,可以不使用new關鍵字,但是這個時候,結構體對象的字段沒有初始值,因為沒有調用構造函數,構造函數中必須為字段賦值,所以,通過new關鍵字創建結構體對象,這個對象的字段就有默認值。

9、棧的訪問速度快,但空間小,堆的訪問速度慢,但空間大,當我們要表示一個輕量級的對象的時候,就定義為結構,以提高速度,根據傳至的影響來選擇,希望傳引用,則定義為類,傳拷貝,則定義為結構。

二、Demo

復制代碼
復制代碼
 1 struct Point
 2     {
 3         public Program p;
 4         private int x;
 5 
 6         public int X
 7         {
 8             get { return x; }
 9             set { x = value; }
10         }
11         private int y;
12 
13         public int Y
14         {
15             get { return y; }
16             set { y = value; }
17         }
18         public void Show()
19         {
20             Console.Write("X={0},Y={1}", this.X, this.Y);
21         }
22         public Point(int x,int y)
23         {
24             this.x = x;
25             this.y = y;
26             this.p = null;
27         }
28         public Point(int x)
29         {
30             this.x = x;
31             this.y = 11;
32             this.p = null;
33         }
34         public Point(int x, int y, Program p)
35         {
36             this.x = x;
37             this.y = y;
38             this.p = p;
39         }
40     }
41     class Program
42     {
43         public string Name { get; set; }
44         static void Main(string[] args)
45         {
46             //Point p = new Point();
47             //p.X = 120;
48             //p.Y = 100;
49             //Point p1 = p;
50             //p1.X = 190;
51             //Console.WriteLine(p.X);
52 
53             //Point p;
54             //p.X = 12;//不賦值就會報錯
55             //Console.WriteLine(p.X);
56             //Point p1 = new Point();
57             //Console.WriteLine(p1.X);//此處不賦值不會報錯,原因見區別8
58 
59             Program p = new Program() { Name="小花"};
60             Point point1 = new Point(10, 10, p);
61             Point point2 = point1;
62             point2.p.Name = "小明";
63             Console.WriteLine(point1.p.Name);//結果為小明,分析見下圖
64         }
65     }
復制代碼
復制代碼

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM