在 C# 中,如何 XML 序列化具有字典作为参数的对象

问题描述

我有这个类(Animal),我需要将其序列化为 XML 文件

[Serializable]
public class Animal 
{
    private String noun;
    private Dictionary<String,Prey> preyByHabitat = new Dictionary<String,Prey>();

    public string Noun { get => noun; set => noun = value; }
    public Dictionary<string,Prey> PreyByHabitat { get => preyByHabitat; set => preyByHabitat = value; }

    public Animal() 
    { }
}

[Serializable]
public class Prey 
{
    private String noun;

    public string Noun { get => noun; set => noun = value; }

    public Prey() { }
}

每次我尝试使用此方法对其进行序列化时:

public void SerializetoXML()
{
    XmlSerializer serializer = new XmlSerializer(typeof(Animal));
    TextWriter textWriter = new StreamWriter(path + @"\Animal.xml");
    serializer.Serialize(textWriter,this);
    textWriter.Close();
}

我收到一个 NotSupportedException,表示它无法序列化 Animal,因为它的一个成员(字典)实现了 IDictionary

为了快速测试,我删除了字典,但没有出现错误

有人可以帮忙吗?

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)