【发布时间】: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