2013-07-23 45 views
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; 
     } 
    } 
+0

您將需要一個無參數構造函數 –

+0

一般來說,當您發佈異常時,您還應該發佈所有內部異常(使用ex.ToString())。對於XML序列化程序的異常尤其如此。內部例外很可能會告訴你到底發生了什麼問題以及如何解決問題。 –

+0

是不是Imterface受保護的關鍵字? – Bit

回答

0

除了你的構造函數帶有一個參數

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

你需要另一個參數的構造函數,像

public Interface() 
{ 
} 

如果您自己沒有聲明構造函數,則會生成一個沒有 參數的構造函數。

然後它應該工作。

相關問題