C#结构体

如果我们要表示一个向量的话需要定义,三个int类型x y z

这样会比较麻烦,不方便管理,我们可以使用结构体

定义结构

struct<typeName>

{

<memberDeclarations>

}

其中<memberDeclarations>是结构体的成员,每个成员的声明如下

<type><name>;

struct Vector3

{

int x;

int y;

int z;

}

示例:

表示一个游戏物体(主角或者敌人)的坐标,需要三个小数

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace jiegouti
{
    //我们可以把结构体当成,几个类型组成了一个新的类型
    //比如下面的这个就是使用了3个float类型的变量,来表示一个坐标类型
    struct Position
    {
        public float x;
        public float y;
        public float z;
    }
    internal class Program
    {
        static void Main(string[] args)
        {
            //通过三个float类型的变量来表示一个敌人的坐标,这样就比较麻烦
            //float enemy1X = 34;
            //float enemy1Y = 1;
            //float enemy1Z = 34;

            //float enemy2X = 34;
            //float enemy2Y = 1;
            //float enemy2Z = 34;

            //当使用结构体声明变量的时候,相当于使用结构体中所有变量去声明
            Position enemy1Position;
            enemy1Position.x = 34;//可以通过.加上属性名来访问结构体中指定的变量
            //使用结构体让程序变得更清晰
            Position enemy2Position;
            enemy2Position.x=35;
        }
    }
}

示例2:

定义一个表示路径的结构,路径有一个方向和距离组成,假定方向只能是东南西北

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace jiegouti
{
   
    enum Direction
    {
        West,
        North,
        East,
        South
    }
    struct Path//结构体可以当成几个类型的结合体
    {
        public float distance;
        public Direction dir;
    }
    internal class Program
    {
        static void Main(string[] args)
        {

            Path path1;
            path1.dir = Direction.East;
            path1.distance = 1000;
        }
    }
}

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值