c# - 从 XML 读取/写入枚举

标签 c# xml enums xmlreader xmlwriter

我正在使用 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/

相关文章:

c# - 寻找 C# 注册表类

c# - 如何使用 C# 在简单的 xsd 元素中查找限制值

c# - C# 中 XML List<T> 反序列化的问题

ios - 将枚举值设置为核心数据对象

java - 使用 Gson 显示枚举及其属性的映射

c# - RegisterStartupScript 和 RegisterClientScriptBlock 的区别?

c# - "ExecuteReader:Connection Property has not been initialized."

c# - 从 URL 读取 XML 文件,结果为空

c++ - 自动生成枚举查找表

c# - 为什么 this.close() 关闭应用程序