gpt4 book ai didi

c# - 在反序列化时跳过无效值

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

问题

是否可以在反序列化时跳过无效值?例如,如果用户在 xml 文件中插入了无效值。

类定义

using Relink.Data.Enum;
using System;
using System.IO;
using System.Xml.Serialization;
using System.ComponentModel;

namespace Relink {

[Serializable]
public class Settings {

internal static XmlSerializer Serializer = new XmlSerializer(typeof(Settings));

public Difficulty Difficulty {
get;
set;
}

public Boolean CaptureMouse {
get;
set;
}

internal void loadDefaults() {
this.Difficulty = Difficulty.Normal;
this.CaptureMouse = false;
}

}

}

序列化方法

// ...
if(!File.Exists(GameDir + SettingsFile)) {
Settings = new Settings();
Settings.loadDefaults();
TextWriter writer = new StreamWriter(GameDir + SettingsFile);
Settings.Serializer.Serialize(writer, Settings);
writer.Close();
writer.Dispose();
} else {
TextReader reader = new StreamReader(GameDir + SettingsFile);
Settings = (Settings)Settings.Serializer.Deserialize(reader);
}
// ...

XML 内容(有效)

<?xml version="1.0" encoding="utf-8"?>
<Settings xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<Difficulty>Normal</Difficulty>
<CaptureMouse>false</CaptureMouse>
</Settings>

XML 内容(无效)

<?xml version="1.0" encoding="utf-8"?>
<Settings xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<Difficulty>Moo</Difficulty>
<CaptureMouse>false</CaptureMouse>
</Settings>

备注

我不想“重置”用户设置,我只想跳过无效的内容并改用默认值。否则我会给你一个 try/catch 结构,然后重新生成 xml 文件。

最佳答案

不幸的是,当遇到未知的 enum 值时,无法抑制 XmlSerializer 中的异常。相反,您需要为此目的创建一个 string 值的属性,并将其序列化而不是 enum 值的属性:

[Serializable]
public class Settings
{
internal static XmlSerializer Serializer = new XmlSerializer(typeof(Settings));

[Browsable(false), EditorBrowsable(EditorBrowsableState.Never)]
[DebuggerBrowsable(DebuggerBrowsableState.Never)]
[XmlElement("Difficulty")]
public string XmlDifficulty
{
get
{
return Difficulty.ToString();
}
set
{
try
{
Difficulty = (Difficulty)Enum.Parse(typeof(Difficulty), value);
}
catch
{
Debug.WriteLine("Invalid difficulty found: " + value);
Difficulty = Difficulty.Normal;
}
}
}

[XmlIgnore]
public Difficulty Difficulty { get; set; }

public Boolean CaptureMouse { get; set; }

internal void loadDefaults()
{
this.Difficulty = Difficulty.Normal;
this.CaptureMouse = false;
}
}

关于c# - 在反序列化时跳过无效值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28782773/

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