找到你要的答案

Q:How to handle WeakReference in DataContract serialization?

Q:如何处理在DataContract序列化WeakReference?

My class uses a readonly WeakReference to store certain data. This class is also serializable via 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.

Simply ignoring the issue is not possible because my code rightly expects the reference object itself to be non-null. Do I have to let go of the readonly and manually check for an re-create the weak reference object during uptime?

我的类使用一个只读WeakReference存储某些数据。这类也是通过DataContract序列化。

我应该如何处理弱引用?我想它是空的回来(目标为空)后反序列化,就好像它已经收集。

仅仅忽略这个问题是不可能的,因为我的代码正确地期望引用对象本身是非空的。我必须放手的只读和手动检查一个重新创建弱引用对象在正常运行吗?

answer1: 回答1:

Since the data contract serializers do not call the default constructor (or any other constructor), you may need to let go of the 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. 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. However, you would still need to let go of the readonly.

(All this assumes that you don't want to store the weakly referenced data when present.)

由于数据合同序列化程序不调用默认构造函数(或任何其他的构造函数),你可能需要放手的只读。你可以通过在一个只有财产就像隐藏领域做出这个有点可口:

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;
        }
    }
}

另一个选择是短路数据协定序列化为您的类通过实现ISerializable然后分配WeakReference在保护MyClass(使用上下文信息,StreamingContext)构造函数。但在这种情况下,我认为治愈可能比疾病更糟。

ondeserializedattribute DataContractSerializer支持回调方法,所以你可以将弱引用而不是检查每一次空。然而,你仍然需要放手的只读。

(假定您不希望在当前时存储弱引用的数据。)

c#  .net  serialization  datacontractserializer  weak-references