gpt4 book ai didi

C#:从文本文件中读取枚举

转载 作者:太空宇宙 更新时间:2023-11-03 17:25:48 24 4
gpt4 key购买 nike

我正在使用 C# 和 XNA 制作 2D 游戏。我目前正在保存和加载,所有数据都存储在文本文件中。

每个 Sprite 都有一个状态:

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<...>>将状态映射到采取适当操作的委托(delegate)(lambda 表达式)。

关于C#:从文本文件中读取枚举,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16148586/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com