你应该如何实现序列化? (接口/约定方面)

发布于 2024-08-06 01:38:26 字数 333 浏览 3 评论 0原文

我根据 Marc 的回答。

这应该是类本身的一部分,即 Apple.Serialize/Deserialize?

尽管在这种情况下反序列化将是静态的,因为您可能没有实例可以调用它。

或者我应该有另一个序列化/反序列化类?如果是这样,这些似乎足够通用?我应该怎么称呼它? AppleSerializer 看起来非常具体。

或者更好的东西?

I implement an xml serialization based on Marc's answer.

Should this be part of the class itself, ie Apple.Serialize/Deserialize?

Although Deserialize would be static in that case, as you might not have an instance to call it on.

Or should I have another class for Serialize/Deserialize? If so, these seem to be generic enough? What should I call it? AppleSerializer seems very specific.

Or something better?

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

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

发布评论

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

评论(2

时常饿 2024-08-13 01:38:26

Yannick M. 提出的技术的一个缺陷是它将您与 XML 序列化的特定实现联系起来。至少,序列化应该是一个虚拟实例操作,以便它可以被派生类覆盖。

另外,不要一开始就使用 XML Serializer。请改用数据契约序列化器。它更高效、更快,但代价是不允许您指定生成的 XML 的确切结构(您可能根本不需要这样做)。

One flaw of the technique proposed by Yannick M. is that it ties you to a particular implementation of XML Serialization. At the very least, serialization should be a virtual instance operation, so that it may be overridden by derived classes.

Also, do not start off using the XML Serializer. Use the Data Contract serializer instead. It is more efficient and faster, at the cost of not allowing you to specify the exact structure of the generated XML (which you may not need to do at all).

聊慰 2024-08-13 01:38:26

Marc 建议的序列化/反序列化代码不会以任何方式链接到您的 Apple 对象。

因此,我建议将它们声明为静态,使它们更加通用,并将它们放入某种实用程序类中。就像这样:

class Util
{
  public static string SerializeToXml<T>(T o) where T: class
  {
    using (var sw = new StringWriter())
    {
      var ser = new XmlSerializer(typeof(T));

      ser.Serialize(sw, o);

      return sw.ToString();
    }
  }

  public static T DeserializeFromXml<T>(string xml) where T: class
  {
    using (var sr = new StringReader(xml))
    {
      var ser = new XmlSerializer(typeof(T))

      return ser.Deserialize(sr) as T;
    }
  }
}

The Serialize/Deserialize code Marc suggested is not linked to your Apple object in any way.

So I would suggest to declare them static make them a little more generic and put them in some sort of utility class. Like so:

class Util
{
  public static string SerializeToXml<T>(T o) where T: class
  {
    using (var sw = new StringWriter())
    {
      var ser = new XmlSerializer(typeof(T));

      ser.Serialize(sw, o);

      return sw.ToString();
    }
  }

  public static T DeserializeFromXml<T>(string xml) where T: class
  {
    using (var sr = new StringReader(xml))
    {
      var ser = new XmlSerializer(typeof(T))

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