protobuf with inheritance?

ε祈祈猫儿з 提交于 2019-12-08 16:41:03

问题


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).



来源:https://stackoverflow.com/questions/4746678/protobuf-with-inheritance

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!