AqlaSolutions / AqlaSerializer

Binary serializer with full .NET support!
http://www.aqla.net
Other
17 stars 3 forks source link

How to model "Lazy" field with Aqla? #28

Closed inethui closed 2 years ago

inethui commented 2 years ago

I have a class which contains a "Lazy" field, how to set it up and make the test case work? Any help is highly appreciated.

[Fact]
public void LazyField()
{
    MetaType metaType = RuntimeTypeModel.Default.Add(typeof(WithLazyField), true);
    metaType.UseConstructor = false;
    ValueMember metaField = metaType.AddField(1, "_lazyField");
    metaField.AsReference = true;

    var obj = new WithLazyField();

    var clone = Serializer.DeepClone(obj);
    Assert.Equal(obj.GetValue(), clone.GetValue());
}

public class WithLazyField
{
    private readonly Lazy<double> _lazyField;

    public WithLazyField()
    {
        _lazyField = new Lazy<double>(() => Calculate());
    }

    public double Calculate()
    {
        return 1.0;
    }

    public double GetValue()
    {
        return _lazyField.Value;
    }
}
AqlaSolutions commented 2 years ago

As far as I remember Lazy is not supported but you can make a surrogate type.

RuntimeTypeModel.Default.Add(typeof(Lazy<double>), false).SetSurrogate(typeof(LazySurrogate<double>));

[SerializableType]
public class LazySurrogate<T>
{
    [SerializableMember(1)]
    public T Data { get; set; }

    public static explicit operator Lazy<T>(LazySurrogate<T> value);// implement
    public static explicit operator LazySurrogate<T>(Lazy<T> value);// implement
}
inethui commented 2 years ago

Thanks a lot!

inethui commented 2 years ago

Also, does Aqla support "Action" and "Func" type fields?

AqlaSolutions commented 2 years ago

Delegates are not supported. They are code pointers and not meant to be serialized.