简体   繁体   中英

Possible to set MetaType callbacks not defined on target type?

I am moving part of my codebase from using protobuf-net via the precompiler and attribute markup to manually adding types and their subtypes and fields to RuntimeTypeModel.Default.

The intent is to disjoin protobuf-net details from the data classes and gain some easily overviewed manoeuvrability for some versioned auto-updating.

So far, so good. I've hit a few snags which I'll bash my head against a bit more to see them solved, however one brick wall does seem to impede progress fairly stubbornly:

I cannot seem to bind OnDeserialized and similar callbacks for my MetaType to anything not defined on the target type.

Initially I was surprised to find MethodInfo variables holding these callbacks rather than simple delegates or events, but figured that combining the string variant of the register call with extension methods for the target type would do the trick. Unfortunately this does not seem to be the case.

Note that the data classes and the serialisation code exists in separate assemblies, so unfortunately I am not able to less-neatly work around this with partial classes either.

Am I missing something or is it simply not possible to register callbacks for the serialisation of a type, defined somewhere other than on that type?

For reference, I am currently using protobuf-net r668.

Edit: Unable to delay further, I have opted for manually running these events around the ProtoBuf serialisation callbacks. Still curious if this could be done though.

That is currently not possible. It is expected that callbacks will be instance methods on the type being used. Note, however, that some other parts of the code allow static methods accepting the instance as a parameter , so in theory it would be possible to change the code to allow something like this to be used as a callback:

public static class Bar
{
    public static void Run(Foo foo)
    {
        Console.WriteLine("Got here");
    }
}

This is not possible right now, however, and could lead to confusion - especially over accessibility. The IL code pulls some tricks to mean that non-public methods can be used as callbacks, but to do this requires declaring the IL to be contextual to the DTO type; it can't cheat the accessibility by pretending the context is also the callback type without introducing a lot more complexity.

So:

  • not currently
  • possible in theory...
  • ...but I am not sure of the utility (how useful this would be, etc) of doing so

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM