Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/276.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 如何将枚举从类传递到窗体?_C#_Winforms_Enums - Fatal编程技术网

C# 如何将枚举从类传递到窗体?

C# 如何将枚举从类传递到窗体?,c#,winforms,enums,C#,Winforms,Enums,我在一个简单的“蛇”类游戏中创建了一个名为“方向”的枚举。但是我不知道如何将值从这个类传递到主窗体 我尝试了什么? 1)我尝试在类和表单中创建相同的枚举,但存在转换问题(Argument1:无法从“Project.Form1.direction”转换为“class.direction” 2)我在传递参数的情况下尝试过,但失败了 然后我尝试了一些愚蠢的事情,我不能在这里提及 我还附上一份声明,也许对你有帮助 //Declaration in the main form is the same as

我在一个简单的“蛇”类游戏中创建了一个名为“方向”的枚举。但是我不知道如何将值从这个类传递到主窗体

我尝试了什么?

1)我尝试在类和表单中创建相同的枚举,但存在转换问题(Argument1:无法从“Project.Form1.direction”转换为“class.direction”

2)我在传递参数的情况下尝试过,但失败了

然后我尝试了一些愚蠢的事情,我不能在这里提及

我还附上一份声明,也许对你有帮助

//Declaration in the main form is the same as the declaration in the class. 

public enum direction { stop, up, down, left, right };

//Each part of enum is for the direction of the snake.

只需定义一次枚举。如果在名为snake的公共类中声明枚举,如下所示:

    public class Snake
    {
        public enum direction { stop, up, down, left, right };

        //rest of class
    }
通过使用类型
Snake.direction

编辑

或者,您可以在任何类之外声明枚举

    public class Snake
    {
        //class
    }

    public enum direction { stop, up, down, left, right };

然后您可以使用
方向
访问枚举

通常最好定义一个,以便名称空间中的所有类都可以同样方便地访问它。但是,枚举也可以嵌套在类或结构中。这里是第一种方法的简单示例,HTH

Direction.cs定义枚举方向

文件
SnakeGame.cs
定义具有类型
Direction

SnakeGameForm.cs
定义表单,在构造函数中它成为类型
SnakeGame
的实例,因此表单每次都知道
方向如何


您可以在类中创建
enum
,并以
公共方向{get;}
namespace Snake.Game.Enums
{
    public enum Direction
    {
        Up,
        Down,
        Left,
        Right
    };
}
using Snake.Game.Enums;

namespace Snake.Game.Classes
{
    public class SnakeGame
    {
        public Direction Direction { get; set; }
    }
}
using System.Windows.Forms;
using Snake.Game.Classes;

namespace Snake.Game.Forms
{
    public partial class SnakeGameForm : Form
    {
        private readonly SnakeGame _game;

        public SnakeGameForm(SnakeGame game)
        {
            InitializeComponent();
            _game = game;
        }

        private void button1_Click(object sender, System.EventArgs e)
        {
            MessageBox.Show($"Direction of snake is '{ _game.Direction}'.");
        }
    }
}