C#结构
C#中的结构是包含许多数据字段和操作这些字段的成员类型,它是用户自定义类型。结构相当于“轻量级的类类型”
创建结构
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace StructDemo
{
struct Point
{
//定义结构的字段
public int x;
public int y;
//定义操作字段的方法
public void Increment()
{
x++;
y++;
}
public void Decrement()
{
x--;
y--;
}
public void Display()
{
Console.WriteLine("x={0},y={1}", x, y);
}
}
class Program
{
static void Main(string[] args)
{
Console.WriteLine("客户端测试");
Point currentPoint;
currentPoint.x=100;
currentPoint.y=100;
currentPoint.Display();
//调整x和y的值
currentPoint.Increment();
currentPoint.Display();
Console.ReadLine();
}
}
}输出结果:
初始化结构
①使用字面量初始化结构
初始化结构由几种方法,在上面的代码中,是在使用结构之前给每个成员字段赋值的,如果,不赋值就会发生编译错误
②使用默认构造函数初始化结构
这种方法的好处是可以取得默认值
修改上面代码:
static void Main(string[] args)
{
Console.WriteLine("客户端测试");
Point currentPoint = new Point();
currentPoint.Display();
//调整x和y的值
currentPoint.Increment();
currentPoint.Display();
Console.ReadLine();
}在第五行中,我们使用了默认的构造函数来初始化结构,这样结构中的字段就会自动取得初始值,再次运行程序,输出如下
可知,int类型字段,取得的初始值为0
使用自定义构造函数初始化结构
我们还可以使用自定义的构造函数来初始化结构类型,这样做的好处是可以在创建变量时指定字段的值,而不用逐个为字段设置成员类型
public Point(int xPoint,int yPoint)
{
x = xPoint;
y = yPoint;
}调用自定义的构造函数
Point currentPoint = new Point(200,200);
这样就可以在创建变量的时候,通过自定义构造函数的参数给结构字段赋值了。
程序输出如下

浙公网安备 33010602011771号