【问题标题】:Serialize a class that contains a list?序列化包含列表的类?
【发布时间】:2013-07-23 17:05:51
【问题描述】:

我可能在这里做错了,但我创建了一个包含列表的类,我需要序列化该列表。 (有没有更好的方法或其他建议让多个接口没有列表?)

我一直在序列化自定义类方面做得很好,但是由于某种原因这个没有解决。

[XmlRoot("interfaces", Namespace = "")]
[XmlInclude(typeof(Interface))]
public class Interfaces
{
    [XmlArray("interfaces")]
    [XmlArrayItem("interface")]
    List<Interface> _IflList = new List<Interface>();
    public List<Interface> IflList
    {
        get { return _IflList; }
        set { _IflList = value; }
    }
    public void Add(Interface objInterface)
    {
        _IflList.Add(objInterface);
    }
}

[XmlType("interface")]
public class Interface
{
    string _name;
    public string name
    {
        get { return _name; }
        set { _name = value; }
    }
    public Interface(string name)
    {
        this._name = name;
    }
}

我在尝试序列化时收到错误There was an error reflecting type 'JunOSConfig.Interfaces':

    public string SerializeObject(object objToSerialize, bool StripXmlVer, bool FormatOutput)
    {
        string strReturn = "";

        XmlSerializerNamespaces xns = new XmlSerializerNamespaces();
        xns.Add("", "");
        Type objType = typeof(JunOSConfig.Interfaces);
        XmlSerializer xs = new XmlSerializer(objToSerialize.GetType());
        XmlWriterSettings xws = new XmlWriterSettings();
        xws.OmitXmlDeclaration = StripXmlVer;

        StringWriter sw = new StringWriter();
        XmlWriter xw = XmlWriter.Create(sw, xws);

        xs.Serialize(xw, objToSerialize, xns);
        strReturn = sw.ToString();

        if (FormatOutput)
        {
            return Convert.ToString(XElement.Parse(strReturn));
        }
        else
        {
            return strReturn;
        }
    }

【问题讨论】:

  • 你需要一个无参数的构造函数
  • 一般来说,当你发布异常时,你也应该发布所有内部异常(使用 ex.ToString())。对于来自 XML 序列化程序的异常尤其如此。内部异常很可能会告诉您确切的问题以及如何解决它。
  • Imterface 不是受保护的关键字吗?
  • 考虑将 Interface(s) 重命名为其他名称,因为 c# 已经有一个 interface 关键字。这令人困惑......
  • 感谢您的提示,我将接口更改为 JunosInterface。我还发现添加 public JunosInterface(string name) 的构造函数会破坏它。如果我把它排除在外,它就会起作用。有什么想法吗?

标签: c# list serialization


【解决方案1】:

除了你的构造函数有一个参数

public Interface(string name)
{
    this._name = name;
}

您将需要另一个无参数构造函数,例如

public Interface()
{
}

如果你自己不声明构造函数,那么没有构造函数 将生成参数。

那么它应该可以工作了。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-07-21
    • 1970-01-01
    • 1970-01-01
    • 2015-07-20
    • 2011-10-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多