我正在使用 XmlWriter 编写一个枚举值,它在 xml 中看起来像这样:
<Tile>Plain</Tile>
writer.WriteValue(tile.ID.ToString()); // ID's type is the enum
Plain 是枚举值之一。现在,当我尝试阅读这篇文章时,虽然它不起作用。
(TileID)reader.ReadElementContentAs(typeof(TileID), null);
我在我的 reader.Name == "Tile"时执行此操作,这应该可以工作,但它显然无法将字符串转换为我的枚举。有没有什么方法可以修复写作,这样我就不必执行 .ToString() (因为如果我不这样做,我会收到错误消息:“TileID cannot be cast to string”。)或修复阅读?
谢谢。
最佳答案
我建议使用 Enum.TryParse
var enumStr = reader.ReadString();
TitleID id;
if (!Enum.TryParse<TitleID>(enumStr, out id)
{
// whatever you need to do when the XML isn't in the expected format
// such as throwing an exception or setting the ID to a default value
}
关于c# - 从 XML 读取/写入枚举,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13573513/