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 } 复制代码 到目前为止,结构体看起来像类,只是关键词不同。话虽这样说,但是结构在一些重要方式还是有别于类。
什么使结构与众不同?
最重要的不同之处是:结构体是值类型,类是引用类型。类和结构体相似,如下:
复制代码 1 public 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 } 在这里插入图片描述