简体   繁体   English

如何处理DataContract序列化中的WeakReference?

[英]How to handle WeakReference in DataContract serialization?

My class uses a readonly WeakReference to store certain data. 我的类使用readonly WeakReference来存储某些数据。 This class is also serializable via DataContract . 此类也可以通过DataContract序列化。

How should I handle the weak reference? 我应该如何处理弱引用? I would like it to come back as empty (target null) after deserialization, just as if it had been collected. 我希望它在反序列化后恢复为空(target null),就好像它已被收集一样。

Simply ignoring the issue is not possible because my code rightly expects the reference object itself to be non-null. 由于我的代码正确地希望引用对象本身为非null,因此无法简单地忽略该问题。 Do I have to let go of the readonly and manually check for an re-create the weak reference object during uptime? 我是否必须放弃readonly并在正常运行时间中手动检查是否重新创建了弱引用对象?

Since the data contract serializers do not call the default constructor (or any other constructor) , you may need to let go of the readonly . 由于数据协定序列化程序不会调用默认构造函数(或任何其他构造函数) ,因此您可能需要放开readonly You could make this somewhat palatable by hiding the field in a get-only property like so: 您可以通过将字段隐藏在仅获取属性中来使此操作变得可口,如下所示:

public class MyClass
{
    WeakReference _m_private_reference_do_not_use_directly;

    WeakReference Reference
    {
        get
        {
            if (_m_private_reference_do_not_use_directly == null)
                Interlocked.CompareExchange(ref _m_private_reference_do_not_use_directly, new WeakReference(null), null);
            return _m_private_reference_do_not_use_directly;
        }
    }
}

The other option would be to short-circuit data contract serialization for your class by making it implement ISerializable and then allocating the WeakReference in the protected MyClass(SerializationInfo info, StreamingContext context) constructor. 另一种选择是通过使实现ISerializable ,然后在protected MyClass(SerializationInfo info, StreamingContext context)构造函数中分配WeakReference来缩短类的数据协定序列化。 But in this case I reckon the cure might be worse than the disease. 但是在这种情况下,我认为治愈的方法可能比疾病还糟。

DataContractSerializer does support OnDeserializedAttribute callback methods , so you could allocate the weak reference there instead of checking for null every time. DataContractSerializer 确实支持OnDeserializedAttribute回调方法 ,因此您可以在那里分配弱引用而不是每次都检查是否为null。 However, you would still need to let go of the readonly . 但是,您仍然需要放开readonly

(All this assumes that you don't want to store the weakly referenced data when present.) (所有这些都假定您不希望在存在弱引用数据时存储它们。)

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

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