The trick here is to use the DynamicType = true
option on a member to your object - as an over-simplified example:
[ProtoMember(12, DynamicType = true)]
public object CouldBeAnything {get;set;}
Re the "string<===>Type map", that is the DynamicTypeFormatting
event on TypeModel
. If you are using the Serializer.*
methods, that is a shortcut (mainly for preserving the v1 API) to the RuntimeTypeModel.Default
serializer instance.
(as a side-note, in writing this I did notice an edge-case that I need to go and fix in the code)
Note: another approach here, rather than using DynamicType
, is to simply configure the model at runtime, for example:
var knownTypes = GetMyKnownTypesAtRuntimeWithUniqueIdentifiers();
var metaType = typeModel[typeof(MyBaseClass)];
foreach(var knownType in knownTypes)
{
metaType.AddSubType(knownType.UniqueIdentifier, knownType.Type);
}
IMO this latter is my preferred option, and will generally be more efficient. Note that it is necessary for the unique-identifiers to be fixed/repeatable, as that is part of the wire format (don't just use the index of the order you find them).
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…