且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

序列化包含类字典成员

更新时间:2023-02-19 20:30:36

您不能序列实现IDictionary的一类。看看这个链接

  

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

?      

答:XmlSerializer的无法处理   课程实施的IDictionary   接口。这部分是由于   进度约束部分是由于   一个哈希表没有事实   有在XSD类型的对应   系统。唯一的解决办法是,   实现自定义的哈希表,做   不执行的IDictionary   接口。

所以,我认为你需要创建自己的版本的词典这一点。勾选此等问题

Expanding upon my earlier problem, I've decided to (de)serialize my config file class which worked great.

I now want to store an associative array of drive letters to map (key is the drive letter, value is the network path) and have tried using Dictionary, HybridDictionary, and Hashtable for this but I always get the following error when calling ConfigFile.Load() or ConfigFile.Save():

There was an error reflecting type 'App.ConfigFile'. [snip] System.NotSupportedException: Cannot serialize member App.Configfile.mappedDrives [snip]

From what I've read Dictionaries and HashTables can be serialized, so what am I doing wrong?

[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();
            }
        }
    }
}

You can't serialize a class that implements IDictionary. Check out this link.

Q: Why can't I serialize hashtables?

A: The XmlSerializer cannot process classes implementing the IDictionary interface. This was partly due to schedule constraints and partly due to the fact that a hashtable does not have a counterpart in the XSD type system. The only solution is to implement a custom hashtable that does not implement the IDictionary interface.

So I think you need to create your own version of the Dictionary for this. Check this other question.