如何最好地保存和加载枚举
本文关键字:加载 枚举 保存 何最好 | 更新日期: 2023-09-27 17:58:21
我正在尝试序列化类中的枚举对象。目前,我将使用二进制读写器来序列化/反序列化。
我的枚举名为SelectionType,并且有一些可能的值。
在我的序列化方法中,我编写了要保存的枚举对象的toString值。
当我读取字符串时,我不知道该如何处理该字符串以将其返回为枚举。我真的不想为每个可能的值都有一个硬编码的情况。
我基本上想说;SelectionType newenumoject=SelectionType.String//其中String是从文件中读取的值。
非常感谢您的帮助:
这是我的
public override void Serialize(Stream stream)
{
System.Diagnostics.Debug.WriteLine("in level select serialize");
using (BinaryWriter writer = new BinaryWriter(stream))
{
//Debug.WriteLine("the type is" + SelectionType.ToString());
writer.Write(SelectionType.ToString());
// Write out the full name of all the types in our stack so we can
// recreate them if needed.
//byte[] bytes = new byte[SelectionType.ToString().Length * sizeof(char)];
//System.BitConverter.GetBytes(mSlectionType);
//writer.Write(bytes, 0, bytes.Length);
}
}
public override void Deserialize(Stream stream)
{
using (BinaryReader reader = new BinaryReader(stream))
{
while (reader.BaseStream.Position < reader.BaseStream.Length)
{
// read a line from our file
string line = reader.ReadString();
// if it isn't blank, we can create a screen from it
if (!string.IsNullOrEmpty(line))
{
Debug.WriteLine("line is" + line);
Type screenType = Type.GetType(line);
//SelectionType selection = Enum.Parse(screenType, line, false);
}
}
// char[] chars = new char[bytes.Length / sizeof(char)];
//System.Buffer.BlockCopy(bytes, 0, chars, 0, bytes.Length);
//new string(chars);
}
如果您关心文件大小和读/写速度,您应该保存枚举的基础值,而不是将其转换为字符串。
// be sure to use the correct backing type for your enum (default is 32-bit int)
writer.Write((int)SelectionType);
//...
selection = (SelectionType)reader.ReadInt32()
您可以只使用Enum.Parse。以下是一个示例:http://dotnetfiddle.net/0e1Ika
var myValue = MyEnum.Value3;
var stringRepresentation = myValue.ToString();
var intRepresentation = (int)myValue;
Console.WriteLine("String-Value: '"{0}'"", stringRepresentation);
Console.WriteLine("Int-Value: {0}", intRepresentation);
var parsedFromString = (MyEnum)Enum.Parse(typeof(MyEnum), stringRepresentation);
var parsedFromInt = (MyEnum)Enum.Parse(typeof(MyEnum), intRepresentation.ToString());
Console.WriteLine("Parsed from string: {0}", parsedFromString);
Console.WriteLine("Parsed from int: {0}", parsedFromInt);
希望能有所帮助。
谨致问候,Chris
ps:嗯,似乎@dave bish更快了:)
如果您知道枚举的类型,则可以使用Enum.Parse
var myValue = (EnumType)Enum.Parse(typeof(EnumType), "StringValue");
[编辑]我看到你在你的例子中已经评论过了——为什么这对你不起作用?