C#编程新技能:深入结构体,提升你的编程实力!
在C# 中,struct是表示数据结构的值类型数据类型。它可以包含参数化构造函数、静态构造函数、常量、字段、方法、属性、索引器、运算符、事件和嵌套类型。struct 可以用于保存不需要继承的小数据值,例如坐标点,键值对和复杂的数据结构。
1.结构声明
使用struct关键字声明结构。默认修饰符是结构及其成员的内部修饰符。
下面的示例声明坐标图的结构。
示例:结构
struct Coordinate
{
public int x;
public int y;
}
与基本类型变量一样,可以使用或不使用new运算符创建struct对象。
示例:创建坐标系结构
struct Coordinate
{
public int x;
public int y;
}
Coordinate point = new Coordinate();
Console.WriteLine(point.x); //输出:0
Console.WriteLine(point.y); //输出:0
上面,使用new关键字创建一个Coordinate(坐标)结构的对象。它调用结构的默认无参数构造函数,该构造函数将所有成员初始化为指定数据类型的默认值。
如果声明一个struct类型的变量而不使用new关键字,则它不调用任何构造函数,因此所有成员都保持未赋值状态。因此,在访问每个成员之前,必须为它们分配值,否则会产生编译时错误。
示例:不使用new关键字创建结构
struct Coordinate
{
publicint x;
publicint y;
}
Coordinate point;
Console.Write(point.x); // 编译时错误
point.x = 10;
point.y = 20;
Console.Write(point.x); //输出:10
Console.Write(point.y); //输出:20
2.结构构造函数
结构(struct)不能包含无参数构造函数。它只能包含参数化构造函数或静态构造函数。
示例:Struct中的参数化构造函数
struct Coordinate
{
public int x;
public int y;
public Coordinate(int x, int y)
{
this.x = x;
this.y = y;
}
}
Coordinate point = new Coordinate(10, 20);
Console.WriteLine(point.x); //输出:10
Console.WriteLine(point.y); //输出:20
必须在参数化构造函数中包含该结构的所有成员,并将其分配给成员;否则,如果任何成员保持未分配状态,C# 编译器将给出编译时错误。
3.结构的方法和属性
struct(结构)可以包含属性、自动实现的属性、方法等,与类相同。
示例:结构的方法和属性
struct Coordinate
{
publicint x { get; set; }
publicint y { get; set; }
publicvoidSetOrigin()
{
this.x = 0;
this.y = 0;
}
}
Coordinate point = Coordinate();
point.SetOrigin();
Console.WriteLine(point.x); //输出:0
Console.WriteLine(point.y); //输出:0
以下struct包括静态方法。
示例:结构体中的静态构造函数
struct Coordinate
{
public int x;
public int y;
public Coordinate(int x, int y)
{
this.x = x;
this.y = y;
}
public static Coordinate GetOrigin()
{
return new Coordinate();
}
}
Coordinate point = Coordinate.GetOrigin();
Console.WriteLine(point.x); //输出:0
Console.WriteLine(point.y); //输出:0
4.结构事件
结构可以包含事件通知订阅者有关某些操作。下面的结构体(struct)包含一个事件。
示例:结构事件
struct Coordinate
{
privateint _x, _y;
publicint x
{
get{
return _x;
}
set{
_x = value;
CoordinatesChanged(_x);
}
}
publicint y
{
get{
return _y;
}
set{
_y = value;
CoordinatesChanged(_y);
}
}
publicevent Action<int> CoordinatesChanged;
}
上面的结构包含coordinateChanged事件,当x或y坐标发生变化时将引发该事件。下面的示例演示如何处理CoordinateChanged事件。
示例:处理结构事件
class Program
{
static void Main(string[] args)
{
Coordinate point = new Coordinate();
point.CoordinatesChanged += StructEventHandler;
point.x = 10;
point.y = 20;
}
static void StructEventHandler(int point)
{
Console.WriteLine("坐标更改为 {0}", point);
}
}
struct是值类型,因此它比类对象快。每当你只想存储数据时,请使用struct。通常,结构适用于游戏编程。但是,与结构相比,传输类对象更容易。因此,当通过网络或其他类传递数据时,请不要使用struct。
公众号搜索:Unity游戏开发之路,获取更多Unity游戏开发知识
更多推荐

所有评论(0)