blob: 3d1385d022e6b8d1db0b282850d42d3b509ea1ea (
plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
|
// Copyright (C) 2025 The Qt Company Ltd.
// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR GPL-3.0-only WITH Qt-GPL-exception-1.0
using System.Runtime.Serialization;
namespace QtVsTools.Json
{
/// <summary>
/// Public interface of objects that allow deferred deserialization of their data.
/// </summary>
/// <typeparam name="TBase">Base type of deferred data</typeparam>
///
public interface IDeferrable<out TBase>
{
TBase Deserialize(IJsonData jsonData);
}
/// <summary>
/// Provides deferred deserialization of a wrapped object, given the base class of a
/// prototyped class hierarchy that will be searched for the actual deserialization class.
/// </summary>
/// <typeparam name="TBase">Base of deferrable class hierarchy</typeparam>
///
[DataContract]
public class DeferredObject<TBase> : Disposable, IDeferredObject
where TBase : Prototyped<TBase>, IDeferrable<TBase>
{
private IJsonData jsonData;
public TBase Object { get; private set; }
object IDeferredObject.Object => Object;
public bool HasData => Object != null;
/// <summary>
/// This constructor is used when serializing, to directly wrap an existing object.
/// </summary>
/// <param name="obj">Object to wrap</param>
///
public DeferredObject(TBase obj)
{
Object = obj;
}
[OnDeserializing] // <-- Invoked by serializer before deserializing this object
private void OnDeserializing(StreamingContext context)
{
// Store JSON data corresponding to this object
jsonData = Serializer.GetCurrentJsonData();
}
/// <summary>
/// Performs a deferred deserialization to obtain a new wrapped object corresponding to the
/// contents of the stored JSON data. The actual deserialization is delegated to the base
/// prototype of the class hierarchy. This prototype is then responsible to find an
/// appropriate class in the hierarchy and map the JSON data to an instance of the class.
/// </summary>
///
public void Deserialize()
{
Atomic(() => Object == null && jsonData != null, () =>
{
Object = Prototyped<TBase>.BasePrototype.Deserialize(jsonData);
jsonData.Dispose();
jsonData = null;
});
}
protected override void DisposeManaged()
{
jsonData?.Dispose();
}
public static implicit operator TBase(DeferredObject<TBase> obj)
{
return obj.Object;
}
}
}
|