gpt4 book ai didi

C# 将枚举类型转换为结构

转载 作者:行者123 更新时间:2023-11-30 19:27:16 25 4
gpt4 key购买 nike

我正在使用 C#,我必须在屏幕上操作一个对象。我设置了一个结构来保存坐标,然后我设置了一个枚举来限制可以移动的方向的数量。

private enum Direction
{
UpperLeft = new Coord(-1, -1),
UpperCenter = new Coord(0, -1),
UpperRight = new Coord(1, -1),
Left = new Coord(-1, 0),
Right = new Coord(1, 0),
LowerLeft = new Coord(-1, 1),
LowerCenter = new Coord(0, 1),
LowerRight = new Coord(1, 1)
};

private struct Coord
{
public int row { get; private set; }
public int col { get; private set; }
public Coord(int r, int c) : this()
{
row = r;
col = c;
}

public static Coord operator +(Coord a, Coord b)
{
return new Coord(a.row + b.row, a.col + b.col);
}
}

基本上我的目标是让屏幕上的对象根据分配的枚举移动。

所以我想像这样假设地使用它:

public class ThingThatMovesToTheLeft
{
Direction dir = Direction.Left;
Coord pos = new Coord(0,0);
public void Move()
{
this.pos = this.dir + this.pos;
}
}

本质上我的问题是如何将我的枚举类型转换回我的结构,以便我可以以这种方式使用它?我似乎无法将其转换回结构。 (此外,VisualStudio 让我毫无怨言地将枚举分配给那些 Coord 结构,所以我认为可以将结构分配给枚举,这是可以接受的做法还是不应该这样做?)

最佳答案

如果你想让复杂的对象静态可用,你需要使用公共(public)静态变量,像这样:

public class Person
{
public string FirstName {get; set; }
public string LastName {get; set; }

public Person(string firstName, string lastName)
{
this.FirstName = firstName;
this.LastName = lastName;
}
}

public static class People
{
public static Person Jack= new Person("Jack", "Andersson");
}

这是因为枚举是特殊结构,在 switch case 结构或管道运算符中具有特殊行为。

编辑:我错了,枚举只是原始类型的语法糖。

我不是专家,所以我并不是说我 100% 确定没有其他方法,但我会像这样为您提供指导类(class):

private static class Directions
{
private static readonly Coord UpperLeft = new Coord(-1, -1);
private static readonly Coord UpperCenter = new Coord(0, -1);
private static readonly Coord UpperRight = new Coord(1, -1),
private static readonly Coord Left = new Coord(-1, 0);
private static readonly Coord Right = new Coord(1, 0);
private static readonly Coord LowerLeft = new Coord(-1, 1);
private static readonly Coord LowerCenter = new Coord(0, 1);
private static readonly Coord LowerRight = new Coord(1, 1);
};

关于C# 将枚举类型转换为结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19154462/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com