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); //2
Console.WriteLine(p2.x); //2
//结构体中成员默认为private的,包括构造函数,p2.z点不出来
//结构体类似类,不过它是值类型,存储在栈上
Point p3 = new Point(1, 2, 3);
p3.Print(); //x = 1,y = 2,z = 3
ChangeValue(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 = 1
x = 3,y = 5,z = 6
x = 8,y = 8,z = 8
x = 9,y = 6,z = 3
*/
}
}
}
参考资料:
- 《唐老狮C#》
本篇结束,感谢您的阅读