代码之家  ›  专栏  ›  技术社区  ›  Ciantic

uri实现了ISerializable,但给出了错误?[复制品]

  •  10
  • Ciantic  · 技术社区  · 16 年前

    可能重复:
    How to (xml) serialize a uri

    据我所知 Uri 实现ISerializable,但这样使用时引发错误:

    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; }
    }
    

    如果 尿嘧啶尿路感染 类型更改为 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); }
        }
    }
    

    谢谢 消化系统 同时指出了我的方法的落后……)

    这将生成XML输出:

    <Server>
        <URI>http://localhost/</URI>
        <Name>test</Name>
    </Server>
    

    我在这里重写了代码,所以代码是可见的。

    4 回复  |  直到 13 年前
        1
  •  9
  •   Anton Gogolev    16 年前

    为了序列化为XML, Uri 类应该有一个无参数的构造函数,但它没有: 尿嘧啶尿路感染 设计为不可变。老实说,我不明白为什么不能 序列化 没有无参数构造函数。

    为了避免这种情况,要么改变 URI 属性类型到 string ,或添加一个调用的属性 _URI 马克 尿嘧啶尿路感染 具有 XmlIgnoreAttribute 重写一下 get 方法AS get { return new Uri(_URI); } .

        2
  •  9
  •   SLaks    16 年前

    实际上,最好的解决方案是反向存储URI属性中的值,并使用字符串访问它。

    例如:

    public class Server
    {
        public string Name { get; set; }
    
        [XmlIgnore]
        public Uri Uri { get; set; }
    
        [XmlElement("URI")]
        public string UriString { 
            get { return Uri.ToString(); }
            set { Uri = new Uri(value); } 
        }
    }
    

    这样,就不可能将其设置为无效的URI(这会在代码中在getter属性中引发异常)。此外,为了遵循标准的.NET大小写准则,应该调用属性 Uri 不是 URI .

        3
  •  2
  •   SLaks    16 年前

    您将二进制序列化与XML序列化混淆。

    XML序列化是一个非常简单的过程,可以保存字段值并将其还原到新对象中。

    二进制序列化功能更强大,允许对象控制序列化行为。这个 ISerializable URI实现的接口仅用于二进制序列化。

        4
  •  0
  •   Beku    16 年前

    内部异常说明:

    无法序列化System.Uri,因为它没有无参数构造函数。

    简单的答案是不能将其序列化为XML。