当前位置: 首页 > news >正文

20250528-C#知识:结构体

C#知识:结构体

结构体是一种自定义数据类型,用户可以根据自身需求设计自己的结构体用来表示某种数据集合。结构体是一种值类型,结合了值类型的优点,避免了引用类型的缺点。本文简单介绍并探究一下C#中的结构体。


  • 结构体一般写在命名空间中
  • 结构体中成员默认为private的,包括构造函数
  • 结构体类似类,不过它是值类型,存储在栈上
  • 结构体支持运算符重载
  • 结构体可以继承接口
  • 结构体中可以存在成员变量、构造函数、成员函数
  • 结构体成员变量可在内部初始化*
  • 结构体的构造函数可以只初始化部分成员变量*
  • 结构体中可以自定义无参构造*
  • 结构体不能有析构函数
  • 结构体不能被继承,成员变量和函数不能用protect关键字修饰
  • 结构体不能被static修饰
  • 结构体不能在内部声明自身类型的结构体变量
namespace LearnStruct
{struct Point : IComparable<Point>{//结构体中可以存在成员变量、构造函数、成员函数//结构体不能有析构函数//结构体不能被继承,成员变量和函数不能用protect关键字修饰//结构体不能被static修饰//结构体不能在内部声明自身类型的结构体变量public int x = 2;   //结构体成员变量在内部初始化public int y;int z;public Point() => Console.WriteLine("结构体无参构造被调用");public Point(int x) => this.x = x;public Point(int x, int y) : this(x) => this.y = y;public Point(int x, int y, int z) : this(x, y) => this.z = z;public int CompareTo(Point other){if (other.x > this.x)return -1;else if (other.x < this.x)return 1;return 0;}public void Print(){Console.Write($"x = {this.x},");Console.Write("y = {0},", this.y);Console.WriteLine("z = " + this.z);}public static Point operator +(Point _self, Point _other){return new Point(_self.x + _other.x, _self.y + _other.y, _self.z + _other.z);}}internal class Program{static void ChangeValue(Point point){point.x += 1;point.y += 1;}static void Main(string[] args){//结构体一般写在命名空间中Point p1 = new Point(); //结构体无参构造被调用Point p2;   //声明结构体变量,需要进行初始化后才能使用p2 = new Point();   //结构体无参构造被调用Console.WriteLine(p1.x);    //2Console.WriteLine(p2.x);    //2//结构体中成员默认为private的,包括构造函数,p2.z点不出来//结构体类似类,不过它是值类型,存储在栈上Point p3 = new Point(1, 2, 3);p3.Print(); //x = 1,y = 2,z = 3ChangeValue(p3);p3.Print(); //x = 1,y = 2,z = 3//结构体支持运算符重载Point p4 = new Point(3, 3, 3);Point p5 = new Point(6, 6, 6);Point p6 = p4 + p5;p6.Print(); //x = 9,y = 9,z = 9//结构体可以继承接口List<Point> points = new List<Point>();points.Add(new Point(2, 3, 1));points.Add(new Point(9, 6, 3));points.Add(new Point(3, 5, 6));points.Add(new Point(8, 8, 8));points.Sort();foreach (Point p in points)p.Print();/*输出:x = 2,y = 3,z = 1x = 3,y = 5,z = 6x = 8,y = 8,z = 8x = 9,y = 6,z = 3*/}}
}

参考资料:

  1. 《唐老狮C#》

本篇结束,感谢您的阅读

在这里插入图片描述

相关文章:

  • Spring AI系列之使用 Mistral AI API 实现函数调用
  • 使用LSTM进行时间序列分析
  • MCU - SPI总线介绍 + W25Qx驱动设计
  • 基于深度学习的三维图像生成项目开发方案
  • SpringAI+MCPServer+MCPClient快速入门
  • 如何优化Elasticsearch的搜索性能?
  • adb查看、设置cpu相关信息
  • failed to bind host port for 0.0.0.0:3306
  • 【 Docker系列】 Docker部署kafka
  • 深度解读漏洞扫描:原理、类型与应用实践
  • 虚拟机中创建虚拟机-window10为例
  • 2025.05.28【Parallel】Parallel绘图:拟时序分析专用图
  • TestStand API编程:在SequenceFile中操作Sequence和Step
  • Vue 3 的 <script setup> 语法糖(持续更新)
  • 零基础设计模式——结构型模式 - 享元模式
  • Conda更换镜像源教程:加速Python包下载
  • 双因子COX 交互 共线性 -spss
  • Windows SMB压缩在低速或者高延迟环境可以帮助提供性能增益
  • UDP数据报
  • 设计模式24——访问者模式
  • 宁波网站开发建设/电商网站订烟平台
  • 网站开发操作可行性报告/怎样做百度推广
  • 做网站鼎盛/网站推广策划案
  • 自己做b2b平台网站建设/如何快速搭建网站
  • 电商网站设计公司可去亿企邦/百度知道合伙人答题兼职
  • 中网建站/长沙网络推广外包