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

标签 c# struct enums

我正在使用 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/

相关文章:

c# - 是什么决定了 WPF 中文本的修剪方式

c# - 有什么技巧可以计算文本文件中的行数吗?

c - 使用结构时出错,C

c - 释放 String 对象

python - 在数据库创建时提供枚举

Objective-C 闭包使用 Swift 枚举

swift - 如何比较两个没有原始类型的枚举实例?

c# - CaSTLe Windsor 组件注册上下文中的 "ForwardedTypes"是什么?

c# - IEnumerable Concat Missing,不包含 'Concat' 的定义

c - 如何修复此结构/链表脚本中的不兼容类型?