序列化包含列表的类?

时间:2013-07-23 17:05:51

标签: c# list serialization

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

我在序列化自定义类时一直没事,但由于某些原因,这个没有用。

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

1 个答案:

答案 0 :(得分:0)

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

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

你需要另一个无参数的构造函数,比如

public Interface()
{
}

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

然后它应该工作。