XmlSerializer - 使用 URI 属性序列化对象时出错

发布于 2024-09-29 15:49:53 字数 359 浏览 0 评论 0原文

我在序列化具有 Uri 属性的类时遇到问题。

System.InvalidOperationException was unhandled
  Message=There was an error reflecting type 'Foo.Story'.
  // ...
  InnerException: System.InvalidOperationException
       Message=There was an error reflecting property 'MyURI'.

我希望这个属性被序列化。有什么方法可以解决这个问题?我应该声明某种转换器并使用 URI 的字符串表示形式吗?

I'm having trouble serializing a class with a Uri property.

System.InvalidOperationException was unhandled
  Message=There was an error reflecting type 'Foo.Story'.
  // ...
  InnerException: System.InvalidOperationException
       Message=There was an error reflecting property 'MyURI'.

I would like this property to be serialized. What is a way around this? Should I declare some sort of a converter, and use the string representation of the URI?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

Oo萌小芽oO 2024-10-06 15:49:53

Uri 类不能序列化为 XML,因为它没有默认构造函数,并且它的所有属性都是只读的。作为解决方法,您可以改为序列化字符串:

[XmlIgnore]
public Uri MyURI { get; set; }

[XmlElement("MyURI")]
public string MyURIAsString
{
    get { return MyURI != null ? MyURI.AbsoluteUri : null; }
    set { MyUri = value != null ? new Uri(value) : null; }
}

The Uri class is not serializable to XML, because all it doesn't have a default constructor and all its properties are read-only. As a workaround, you can serialize a string instead:

[XmlIgnore]
public Uri MyURI { get; set; }

[XmlElement("MyURI")]
public string MyURIAsString
{
    get { return MyURI != null ? MyURI.AbsoluteUri : null; }
    set { MyUri = value != null ? new Uri(value) : null; }
}
憧憬巴黎街头的黎明 2024-10-06 15:49:53

它必须是 XmlSerializer 吗?
DataContractSerializer 可以工作:

    using (var stream = File.Create(@"c:\Uri.xml"))
        new DataContractSerializer(typeof(Uri)).WriteObject(stream, new Uri(@"http://www.contoso.com/"));

这是一个很好的 文章 总结了差异

Does it have to be XmlSerializer ?
DataContractSerializer would work:

    using (var stream = File.Create(@"c:\Uri.xml"))
        new DataContractSerializer(typeof(Uri)).WriteObject(stream, new Uri(@"http://www.contoso.com/"));

Here is a nice article that sums up the differences

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文