protobuf with inheritance?

2019-06-16 10:39发布

问题:

Is it possible to use protobuf with classes who inherit?

I want to do something like this

class Expr;
class AddExpr : Expr;
class CallFunc: Expr;

class FunctionBody{
    repeatable Expr expr;
}

回答1:

Not in the core implementation - you would want to use encapsulation instead.

However if you are using just protobuf-net, as code-first, I hack around it:

[ProtoInclude(1, typeof(AddExpr))]
[ProtoInclude(2, typeof(CallFunc))]
[ProtoContract]
class Expr {}

[ProtoContract]
class AddExpr : Expr {} 
[ProtoContract]
class CallFunc: Expr {}

[ProtoContract]
class FunctionBody{
    private List<Expr> expressions;
    [ProtoMember(1)]
    public List<Expr> Expressions {
        get { return expressions ?? (expressions = new List<Expr>()); }
    }
}

Of course, I'm assuming there is some additional detail in the classes - "as is" you could just use an enum (which is well-supported).