的System.Uri实现ISerializable的,但给错误? [英] System.Uri implements ISerializable, but gives error?

查看:364
本文介绍了的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); }.

这篇关于的System.Uri实现ISerializable的,但给错误?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆