c# - 如何在 streamwriter 中保存枚举项?

标签 c# enums streamwriter

我有一个enum list(?),我想把它保存在一个StreamWriter中,但是我不知道怎么保存,我的意思是:

TextWriter gPieza = new StreamWriter("Pieza.txt", true);
gPieza.WriteLine();
gPieza.Close();

我不知道如何将它放在 WriteLine 中。我尝试放入 Class.EnumName.ToString(); 但它不允许,在 de EnumName 之后出现的是 Enum 具有的不同内容。

这些是我的枚举列表:

    public enum Types
    {
        Vacio,
        Peon,
        Torre,
        Caballo,
        Alfil,
        Reina,
        Rey
    }

    public enum Colors
    {
        White,
        Black
    }

这些是国际象棋游戏的一部分,我需要保存用户在棋盘上放的是什么棋子,棋子放在什么位置。

    Types _type;
    Colors _color;
    Point _coord;

最佳答案

对于只写枚举,

var myEnums = new List<MyEnum>
                  {
                      MyEnum.Value1,
                      MyEnum.Value2,
                      MyEnum.Value1, 
                      MyEnum.Value1,
                      MyEnum.Value2,
                      MyEnum.Value1, 
                      MyEnum.Value1,
                      MyEnum.Value2,
                      MyEnum.Value1
                  };

var streamWriter = new StreamWriter("test.txt");

foreach (var myEnum in myEnums)
{
    streamWriter.WriteLine(myEnum);
}

streamWriter.Close();

如果要写入实际值

streamWriter.WriteLine((int)myEnum);

更新 要编写多种类型的枚举,您可以编写一些方法,例如,

public static void WriteEnums<T>(List<T> enums)
{
    var streamWriter = new StreamWriter("test.txt");

    foreach (var myEnum in enums)
    {
        streamWriter.WriteLine(myEnum);
    }

    streamWriter.Close();
}

然后调用它,

var types = new List<Types>
                  {
                      Types.Alfil,
                      Types.Peon,
                      Types.Vacio
                  };

var colorses = new List<Colors>
                   {
                       Colors.Black, Colors.Black, Colors.White
                   };


WriteEnums(colorses);
WriteEnums(types);

关于c# - 如何在 streamwriter 中保存枚举项?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22110473/

相关文章:

c# - 在 C# 中构建结构时出错

c# - 在 C# 中重用字节数组的优点/缺点是什么?

c# - c#中初始化集合类似于Java匿名类语法

c - 如何在 C 中为枚举赋值?

c# - 通过枚举值+依赖注入(inject)创建实例

c# - 为什么 StreamWriter 会覆盖我的文件?

c# - property.GetValue() 中的参数计数不匹配

c# - 将 txt 文件保存到错误的位置

c# HttpWebRequest POST'ing 失败

Java 枚举和 valueOf 反序列化