的System.Uri实现ISerializable的,但给错误?
可能重复:
如何(XML)序列化的URI
据我所知,乌里
实现ISerializable的,但像他这样使用时抛出错误:
To my knowledge Uri
implements ISerializable, but throws error when used like this:
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; }
}
工作得很好,如果乌里
类型更改为字符串
。
任何人都知道什么是罪魁祸首?
Anyone knows what is the culprit?
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 的也指出我的方法的落后...)
(Thanks for SLaks also pointing out the backwardness of my method...)
这产生XML输出:
This produces XML output:
<Server>
<URI>http://localhost/</URI>
<Name>test</Name>
</Server>
我重写了它在这里,所以在code是可见的。
I rewrote it here so the code is visible.
为了被序列化到XML,乌里
类应该有一个无参数的构造函数,它没有按' T:乌里
的设计是不可变的。老实说,我不明白为什么它不能的连载的,而不必一个参数的构造函数。
In order to be serialized to XML, Uri
class should have a parameterless constructor, which it doesn't: Uri
is designed to be immutable. Honestly, I can't see why it cannot be serialized without having a parameterless constructor.
要绕过这个,要么改变 URI
属性类型字符串
,或添加一个名为多了一个属性 _URI
标记 URI
与 XmlIgnoreAttribute
并重写它的获得
方法 {返回新的URI(_URI); }
。
To circumvent this, either change URI
property type to string
, or add one more property called _URI
, mark URI
with XmlIgnoreAttribute
and rewrite it's get
method as get { return new Uri(_URI); }
.