[英]C#: Reading enums from text file
我正在用C#和XNA制作2D游戏。 我目前正在保存和加载,所有数据都存储在文本文件中。
每个精灵都有一个状态:
public enum SpriteState
{
Alive,
Dead,
Chasing,
Sleeping,
Waiting
}
保存时,我只是执行以下代码行:
StreamWriter.WriteLine(gameState);
现在,当我加载游戏时,我必须阅读文本文件的这一行,将其存储在字符串变量中,并执行以下操作:
string inType = StreamReader.ReadLine();
if(inType == "Alive")
//Set the sprites state to alive
else if(inType == "Dead")
//Set the sprites state to alive
依此类推...所以我的问题是:是否有更好的方法从文本文件中读取枚举类型并进行分配?
非常感谢
您正在寻找
(SpriteState) Enum.Parse(typeof(SpriteState), inType)
这会将字符串解析为枚举值。
您可能还希望拥有Dictionary<SpriteState, Action<...>>
将状态映射到采取适当操作的委托(lambda表达式)。
尝试这个:
Enum.Parse(typeof(SpriteState), yourString);
您也可以使用以下方法:
public static T ParseEnum<T>(string value)
{
return (T)Enum.Parse(typeof(T), value, true);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.