C# 結構體:定義、示例、最佳實踐和陷阱
阿新 • • 發佈:2022-03-27
C#結構體:從C/C++時代遷移過來的經典。結構體與類相似,也有大量不同之處 。結構體對做為C#開發者來說有很多價值。一般不需要用到結構體,但是有些方面結構體比類做得好。
結構體是什麼?
結構體是class物件的小姐妹。初相見,他們之間區別不大。他們都包含不同型別的欄位的集合,如下
1 public struct Flower 2 { 3 public string name; 4 protected int beautyRating; 5 private bool isVascular; 6 }
可以試一下結構體。做為一種簡單的資料結構,可以將結構體視為一種欄位包。可能你會用結構體做為資料傳輸物件,或者可能你想要在其它基於欄位值的地方執行一些邏輯。
也可以用結構體封裝行為,如下:
1 public struct FlowerWithBehavior 2 { 3 string name; 4 int beautyRating; 5 bool isVascular; 6 7 public void makeBeautiful() 8 { 9 beautyRating = 10; 10 } 11 }
到目前為止,結構體看起來像類,只是關鍵詞不同。話雖這樣說,但是結構在一些重要方式還是有別於類。
什麼使結構與眾不同?
最重要的不同之處是:結構體是值型別,類是引用型別。類和結構體相似,如下:
1public struct FlowerStruct 2 { 3 string name; 4 int beautyRating; 5 bool isVascular; 6 7 public FlowerStruct(string name, int beautyRating, bool isVascular) 8 { 9 this.name = name; 10 this.beautyRating = beautyRating; 11 this.isVascular = isVascular;12 } 13 } 14 15 public class FlowerClass 16 { 17 public string name; 18 public int beautyRating; 19 public bool isVascular; 20 21 public FlowerClass(string name, int beautyRating, bool isVascular) 22 { 23 this.name = name; 24 this.beautyRating = beautyRating; 25 this.isVascular = isVascular; 26 } 27 }
儘管看起來相似,但是類和結構體有不同之處:
1 public void Test_Struct_Vs_Class_Equality() 2 { 3 FlowerStruct struct1 = new FlowerStruct("Daisy", 3, true); 4 FlowerStruct struct2 = new FlowerStruct("Daisy", 3, true); 5 6 FlowerClass class1 = new FlowerClass("Daisy", 3, true); 7 FlowerClass class2 = new FlowerClass("Daisy", 3, true); 8 9 Assert.Equal(struct1, struct2); 10 Assert.NotEqual(class1, class2); 11 }
1 using System; 2 using System.Collections.Generic; 3 using System.Linq; 4 using System.Text; 5 using System.Drawing; 6 using System.Windows.Forms; 7 using Microsoft.VisualStudio.TestTools.UITesting; 8 9 namespace Struct_And_Class 10 { 11 class Program 12 { 13 static void Main(string[] args) 14 { 15 FlowerStruct struct1 = new FlowerStruct("Daisy",3,true); 16 FlowerStruct struct2 = new FlowerStruct("Daisy", 3, true); 17 18 FlowerClass class1 = new FlowerClass("Daisy",3,true); 19 FlowerClass class2 = new FlowerClass("Daisy", 3, true); 20 21 bool Result1 = Equals(struct1,struct2); 22 bool Result2 = Equals(class1,class2); 23 24 Console.WriteLine("結構體對比結果是{0}",Result1); 25 Console.WriteLine("類的對比結果是{0}",Result2); 26 } 27 } 28 29 public struct FlowerStruct 30 { 31 string name; 32 int beautyRating; 33 bool isVascular; 34 35 public FlowerStruct(string name, int beautyRating,bool isVascular) 36 { 37 this.name = name; 38 this.beautyRating = beautyRating; 39 this.isVascular = isVascular; 40 } 41 } 42 43 public class FlowerClass 44 { 45 string name; 46 int beautyRating; 47 bool isVascular; 48 49 public FlowerClass(string name, int beautyRating, bool isVascular) 50 { 51 this.name = name; 52 this.beautyRating = beautyRating; 53 this.isVascular = isVascular; 54 } 55 } 56 }完整程式碼
如上面完整程式碼所呈現的,對於結構體來說,只要是內部是相等相同的,結果就是相等的;而類不相等,與欄位沒有關係。