C# 结构体:定义、示例

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 }
在这里插入图片描述

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

光怪陆离的节日

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值