可序列化属性.NET
我在 .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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
如果不知道类是如何实现的,则对其进行序列化是不安全的,并且这样做可能会导致对象被巧妙地破坏。这就是为什么类设计者必须有意添加
Serialized
属性,让运行时知道这是一个安全的操作。自动将该属性添加到任何类可能是一个坏主意。如果您确实需要序列化一个不可序列化的类,您可以手动完成:
如果做不到这一点,您应该考虑除序列化之外的其他保存状态的方法。
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:Failing that, you should look at other ways of preserving state besides serialization.
您无法在运行时修改属性。仅在源中。
You can't modify attributes in runtime. Only in source.
您可以使用反射来迭代任何类/实例的属性。
但你必须制作一个自定义序列化器。
You can use reflection to iterate over the properties of any class/instance.
But you have to make a custom serializer.
.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.
考虑使用 typeof(yourType).IsSerializable...
Consider using typeof(yourType).IsSerializable...