Google protobuff枚举命名约定

时间:2018-02-21 17:39:39

标签: enums enumeration google-protocol-buffer

我无法找到有关Google protobuff枚举值的命名约定的具体指导,以避免命名冲突。

由于protobuff枚举是全局的,因此以下内容会导致命名冲突:

enum CommissionType {
    UNKNOWN = 0;
    AMOUNT = 1;
    PERCENTAGE = 2;
}

enum ChargeType {
    UNKNOWN = 0;
    AMOUNT = 1;
    PERCENTAGE = 2;
}

因此,我收到的建议是包含TypeName,但不清楚约定是否要添加或附加该类型名称(如下所示)。我个人认为,附加它并获得intellisense的好处更具可读性,但我无法找到任何证据支持或反对。如果您能链接到任何示例或讨论,我将不胜感激。感谢。

enum CommissionType {
    COMMISSION_TYPE_UNKNOWN = 0;
    COMMISSION_TYPE_AMOUNT = 1;
    COMMISSION_TYPE_PERCENTAGE = 2;
}

enum CommissionType {
    UNKNOWN_COMMISSION_TYPE = 0;
    AMOUNT_COMMISSION_TYPE = 1;
    PERCENTAGE_COMMISSION_TYPE = 2;
}

1 个答案:

答案 0 :(得分:0)

好吧,经过一些挖掘和实验后,我自己回答了这个问题。 在此发布完整性。

正确的约定是前缀枚举值中的类型名称。 c#transpiler足够聪明,可以从生成的代码中删除Type Name。如果附加了TypeName,则不会发生这种情况:

enum CommissionType {
    COMMISSION_TYPE_UNKNOWN = 0;
    COMMISSION_TYPE_AMOUNT = 1;
    COMMISSION_TYPE_PERCENTAGE = 2;
}

这将由protobuff转换器解析为生成的代码:

#region Designer generated code
...
  public enum CommissionType {
    [pbr::OriginalName("COMMISSION_TYPE_UNKNOWN")] Unknown = 0,
    [pbr::OriginalName("COMMISSION_TYPE_AMOUNT")] Amount = 1,
    [pbr::OriginalName("COMMISSION_TYPE_PERCENTAGE")] Percentage = 2,
  }
...
#endregion Designer generated code

以下列清晰易用的方式消费:

TypeOfCommission = CommissionType.Percentage,

为了完整性,我最初认为最好的解决方案,更可读的* .proto代码,最终会产生不良结果:

enum CommissionType {
    UNKNOWN_COMMISSION_TYPE = 0;
    AMOUNT_COMMISSION_TYPE = 1;
    PERCENTAGE_COMMISSION_TYPE = 2;
}

#region Designer generated code
...
public enum CommissionType {
    [pbr::OriginalName("UNKNOWN_COMMISSION_TYPE")] UnknownCommissionType = 0,
    [pbr::OriginalName("AMOUNT_COMMISSION_TYPE")] AmountCommissionType = 1,
    [pbr::OriginalName("PERCENTAGE_COMMISSION_TYPE")] PercentageCommissionType = 2,
  }
...
#endregion Designer generated code

使用此枚举:

TypeOfCommission = CommissionType.PercentageCommissionType,