MemoryPack icon indicating copy to clipboard operation
MemoryPack copied to clipboard

Support external union metadata

Open Genbox opened this issue 2 years ago • 2 comments

It is impossible to serialize classes that are defined in external libraries, so it would be nice if you could provide the same information as MemoryPackUnion, but via a builder system instead.

From your own example. Instead of doing this:

[MemoryPackable]
[MemoryPackUnion(0, typeof(FooClass))]
[MemoryPackUnion(1, typeof(BarClass))]
public partial interface IUnionSample { }

[MemoryPackable]
public partial class FooClass : IUnionSample { }

[MemoryPackable]
public partial class BarClass : IUnionSample { }

It would be nice to do this:

These 3 classes are provided by an external library that can't take a dependency on MemoryPack. so they look like this (in the library):

public interface IUnionSample { }
public class FooClass : IUnionSample { }
public class BarClass : IUnionSample { }

Since they are not partial, we can't use source generator etc. - instead we create a custom formatter. But in order to support union/polymorphism, we need to provide the inheritance relationships somehow. It could be done like this:


UnionBuilder ub = new UnionBuilder(typeof(IUnionSample));
ub.AddUnion(0, typeof(FooClass));
ub.AddUnion(1, typeof(BarClass));

//Then we provide 'ub' to the serializer in some way.

Note that I just come up with an example on the spot. I have no preference for how the above is achieved.

Genbox avatar Oct 01 '22 13:10 Genbox

Since it is Source Generator-based, it cannot be generated by dynamic code. Instead, how about the following API?

[MemoryPackFormatter(typeof(IUnionSample))]
[MemoryPackUnion(0, typeof(FooClass))]
[MemoryPackUnion(1, typeof(BarClass))]
public partial class UnionFormatter
{
}

neuecc avatar Oct 01 '22 23:10 neuecc

The information just need to be conveyed somehow externally from the POCO classes. If that is the only way, then I guess it would work :)

Genbox avatar Oct 02 '22 13:10 Genbox

still not available in v1.8.3? but i saw the document

xiaoyuvax avatar Nov 23 '22 09:11 xiaoyuvax

I've released v1.8.5, it includes MemoryPackUnionFormatterAttribute.

neuecc avatar Nov 23 '22 11:11 neuecc