可能的重复:
如何 (xml) 序列化 uri https://stackoverflow.com/questions/1036492/how-to-xml-serialize-a-uri
据我所知Uri
实现 ISerialized,但像这样使用时会抛出错误:
XmlSerializer xs = new XmlSerializer(typeof(Server));
xs.Serialize(Console.Out, new Server { Name = "test", URI = new Uri("http://localhost/") });
public class Server
{
public string Name { get; set; }
public Uri URI { get; set; }
}
工作得很好,如果Uri
类型更改为string
.
有谁知道罪魁祸首是什么?
提出的解决方案安东·戈戈列夫:
public class Server
{
public string Name { get; set; }
[XmlIgnore()]
public Uri Uri;
[XmlElement("URI")]
public string _URI // Unfortunately this has to be public to be xml serialized.
{
get { return Uri.ToString(); }
set { Uri = new Uri(value); }
}
}
(感谢SLaks还指出了我的方法的落后...)
这会产生 XML 输出:
<Server>
<URI>http://localhost/</URI>
<Name>test</Name>
</Server>
我在这里重写了它,以便代码可见。
为了序列化为 XML,Uri
类应该有一个无参数构造函数,但它没有:Uri
被设计为不可变的。老实说,我不明白为什么不能连载的没有无参数构造函数。
为了避免这种情况,要么改变URI
属性类型为string
,或者再添加一个名为_URI
, mark URI
with XmlIgnoreAttribute
并重写它get
方法如get { return new Uri(_URI); }
.
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)