MemoryPack
MemoryPack copied to clipboard
Support external union metadata
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.
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
{
}
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 :)
still not available in v1.8.3? but i saw the document
I've released v1.8.5
, it includes MemoryPackUnionFormatterAttribute
.