小编典典

序列化包含Dictionary成员的类

c#

扩展我之前的问题,我决定对配置文件类进行反序列化,该类效果很好。

我现在想存储的驱动器号关联数组映射(关键是驱动器盘符,价值是网络路径)和使用都试过DictionaryHybridDictionaryHashtable这个,但是打电话时,我总是得到下面的错误ConfigFile.Load()或者ConfigFile.Save()

反映类型’App.ConfigFile’的错误。[snip]
System.NotSupportedException:无法序列化成员App.Configfile.mappedDrives [snip]

从我看过的书中可以将Dictionary和HashTables序列化,那么我在做什么错呢?

[XmlRoot(ElementName="Config")]
public class ConfigFile
{
    public String guiPath { get; set; }
    public string configPath { get; set; }
    public Dictionary<string, string> mappedDrives = new Dictionary<string, string>();

    public Boolean Save(String filename)
    {
        using(var filestream = File.Open(filename, FileMode.OpenOrCreate,FileAccess.ReadWrite))
        {
            try
            {
                var serializer = new XmlSerializer(typeof(ConfigFile));
                serializer.Serialize(filestream, this);
                return true;
            } catch(Exception e) {
                MessageBox.Show(e.Message);
                return false;
            }
        }
    }

    public void addDrive(string drvLetter, string path)
    {
        this.mappedDrives.Add(drvLetter, path);
    }

    public static ConfigFile Load(string filename)
    {
        using (var filestream = File.Open(filename, FileMode.Open, FileAccess.Read))
        {
            try
            {
                var serializer = new XmlSerializer(typeof(ConfigFile));
                return (ConfigFile)serializer.Deserialize(filestream);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message + ex.ToString());
                return new ConfigFile();
            }
        }
    }
}

阅读 382

收藏
2020-05-19

共1个答案

小编典典

您不能序列化实现IDictionary的类。查看此链接

问:为什么我不能序列化哈希表?

答:XmlSerializer无法处理实现IDictionary接口的类。这部分是由于调度约束,部分是由于哈希表在XSD类型系统中没有对应项。唯一的解决方案是实现不实现IDictionary接口的自定义哈希表。

因此,我认为您需要为此创建自己的词典版本。检查另一个问题

2020-05-19