2

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

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

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

1 回答 1

0

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

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

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

public Interface()
{
}

如果自己不声明构造函数,会生成一个不带参数的构造函数。

然后它应该工作。

于 2013-07-23T19:49:08.510 回答