简体   繁体   English

序列化对静态只读成员的引用

[英]Serializing a reference to a static readonly member

I have a piece of code that looks something like this: 我有一段看起来像这样的代码:

public static class MyStaticClass
{
    public static readonly MyObject1 object1 = new MyObject1();
}

[Serializable]
public class MyOtherClass
{
    public MyObject1 Obj { get; } = MyStaticClass.object1;
}

When deserializing (using default binary serialization) an instance of MyOtherClass, Obj is no longer the same object as MyStaticClass.object1. 当反序列化(使用默认二进制序列化)MyOtherClass的实例时,Obj不再是与MyStaticClass.object1相同的对象。 Is there any way to automatically retain that reference, or am I simply going to have to reconstruct it via a string or some other identifier? 有没有办法自动保留该引用,或者我只是需要通过字符串或其他标识符重建它? If so, what would be the recommended way to cleanly rebuild that reference? 如果是这样,那么干净地重建该引用的推荐方法是什么?

Is there any way to automatically retain that reference 有没有办法自动保留该引用

That depends on your definition of "automatically", but assuming you mean "without writing any additional code", the answer is "no". 这取决于你对“自动”的定义,但假设你的意思是“不写任何额外的代码”,答案是“不”。

Serialization deals with data, not objects. 序列化处理数据,而不是对象。 When you deserialize the object, all that the stock deserialization implementations know is the data that was stored. 反序列化对象时,库存反序列化实现知道的所有内容都是存储的数据。 Which is as it should be; 这是应该的; a general-purpose deserialization implementation wouldn't even know where to look to match an object like that and use an existing reference, so it'd have to search the entire in-memory object graph from all roots. 一个通用的反序列化实现甚至不知道在哪里寻找匹配这样的对象并使用现有的引用,因此它必须从所有根搜索整个内存中的对象图。

You will need to provide a mechanism to deal with this explicitly. 您需要提供一种机制来明确地处理这个问题。 Depending on what serialization method you're using, you may be able to customize the entire process so that you don't have to serialize the entire MyObject1 data, but instead just store some kind of marker that your customized deserialization can use to signify the original object. 根据您正在使用的序列化方法,您可以自定义整个过程,这样您就不必序列化整个MyObject1数据,而只是存储某种标记,您的自定义反序列化可以用来表示原始物体。

Alternatively, your customization could just rely on MyObject1 implementing some type of equality, so that you can compare the deserialized object and replace its reference with the "stock" reference if the two objects are equal. 或者,您的自定义可能只依赖于MyObject1实现某种类型的相等性,这样您就可以比较反序列化的对象,并在两个对象相等的情况下将其引用替换为“stock”引用。

If you're using a serialization method that supports the IObjectReference.GetRealObject() mentioned in the comments , that would work too. 如果您正在使用支持注释中提到的IObjectReference.GetRealObject()的序列化方法,那么它也会起作用。

But whatever you do, you're going to have to do it yourself. 但无论你做什么,你都必须自己做。 (Or use a third-party library that supports a feature like that out of the box…I'm not aware of any, but that doesn't mean it doesn't exist.) (或者使用支持开箱即用功能的第三方库...我不知道,但这并不意味着它不存在。)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM