简体   繁体   中英

How can I save enum items in a streamwriter?

I have a enum list (?) and I want to save it in a StreamWriter , but I don't know how to save it, what I mean is:

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

I don't know how to put it in the WriteLine. I tried to put Class.EnumName.ToString(); but it won't let me, what appears after de EnumName is the different thing that the Enum has.

These are my enum lists :

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

    public enum Colors
    {
        White,
        Black
    }

These are part of a chess game, I need to save what piece the user put on the checkerboard and in what position the Piece was placed.

    Types _type;
    Colors _color;
    Point _coord;

For writing just the enum,

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();

If you want to write the actual values

streamWriter.WriteLine((int)myEnum);

Update For writing multiple type of enum you can write some method like,

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

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

    streamWriter.Close();
}

And call it,

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);
foreach( var enumValue in Enum.GetValues(typeof(MyEnum))) 
{ 
     Console.WriteLine(enumValue); // or enumValue.ToString()
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM