我正在用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表达式)。

08-06 19:02