可序列化属性.NET

发布于 2024-10-04 03:41:03 字数 309 浏览 4 评论 0原文

我在 .NET 中使用二进制序列化来克隆对象。我自己的任何类都必须使用 属性进行标记,以便序列化程序能够处理该类。然而,由于这是一个将在任何对象上使用的函数,我想知道:

是否可以让序列化器序列化该对象,即使它没有标记 属性?如果没有,是否有办法将该属性“自动应用”到任何类?

编辑。我主要关心的是我需要能够克隆 .NET Framework 中已存在的 POCO 对象。所有这些都已经可以序列化了吗?

I'm using Binary Serialization in .NET to clone objects. Any of my own classes I must mark with the <Serializable()> attribute in order for the serializer to process the class. However since this is a function that will be used on any object, I was wondering:

Is it possible to have the serializer serialize the object even if it isn't marked with the <Serializable()> attribute? If not, is there a way to "auto-apply" the attribute to any class?

Edit. My main concern is that I need to be able to clone POCO objects that already exist in the .NET Framework. Are all those already serializable as well?

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

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

发布评论

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

评论(5

蝶…霜飞 2024-10-11 03:41:03

如果不知道类是如何实现的,则对其进行序列化是不安全的,并且这样做可能会导致对象被巧妙地破坏。这就是为什么类设计者必须有意添加 Serialized 属性,让运行时知道这是一个安全的操作。自动将该属性添加到任何类可能是一个坏主意。

如果您确实需要序列化一个不可序列化的类,您可以手动完成:

  1. 找出某种方法将您的问题类与替代表示形式相互转换。
  2. 使用其他类进行序列化,根据需要来回转换。

如果做不到这一点,您应该考虑除序列化之外的其他保存状态的方法。

Without knowing how a class is implemented, it isn't safe to serialize it, and doing so could lead to subtly-broken objects. That's why a class designer must intentionally add the Serializable attribute, letting the runtime know that this is a safe operation. Automatically adding that attribute to any class is probably a bad idea.

If you really need to serialize a class that isn't Serializable, you can do it manually:

  1. Figure out some way to convert your problem class to and from an alternate representation.
  2. Use that other class for serialization, converting back and forth as necessary.

Failing that, you should look at other ways of preserving state besides serialization.

多情出卖 2024-10-11 03:41:03

您无法在运行时修改属性。仅在源中。

You can't modify attributes in runtime. Only in source.

池予 2024-10-11 03:41:03

您可以使用反射来迭代任何类/实例的属性。
但你必须制作一个自定义序列化器。

You can use reflection to iterate over the properties of any class/instance.
But you have to make a custom serializer.

夕色琉璃 2024-10-11 03:41:03

.NET 框架本身通常在所有有意义的类和结构中提供序列化支持,因此框架本身的类很可能可以与您的克隆一起正常工作。但是,如果您使用任何第三方库,您可能会遇到麻烦,不幸的是,这些库通常没有适当的序列化支持。

The .NET framework itself usually provides serialization support in all classes and structs where this does make sense, so it is likely that classes from the framework itself will work fine with your cloning. However, you may get in trouble if you use any 3rd-party libraries, which unfortunately quite often don't have proper serialization support.

情归归情 2024-10-11 03:41:03

考虑使用 typeof(yourType).IsSerializable...

Consider using typeof(yourType).IsSerializable...

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