繁体   English   中英

C# 中的协议缓冲区和类型安全枚举

[英]Protocol Buffers and Typesafe Enums in C#

我正在尝试序列化一些我实现的类型安全枚举,就像这个问题的答案一样。 当我序列化一个包含对FORMS引用的对象时(来自我链接的答案),我希望在反序列化时恢复对静态字段FORMS的引用。

我有一个解决方案,但它看起来很糟糕,因为我必须将它添加到任何包含类型安全枚举的类中。 它几乎只是使用回调来存储和检索枚举的value字段:

    public class SomethingContainingAnAuthenticationMethod
    {
      [ProtoMember(1)] 
      public int AuthenticationMethodDataTransferField { get; set; }

      public AuthenticationMethod AuthenticationMethod { get; set; }

      [ProtoBeforeSerialization]
      public void PopulateDataTransferField()
      {
        AuthenticationMethodDataTransferField = AuthenticationMethod.value;
      }

      [ProtoAfterDeserialization]
      public void PopulateAuthenticationMethodField()
      {
        AuthenticationMethod = AuthenticationMethod.FromInt(AuthenticationMethodDataTransferField);
      }
    }

任何其他想法将不胜感激。

通过链接示例中的答案,最简单的方法可能是:

[ProtoContract]
public class SomethingContainingAnAuthenticationMethod
{
  [ProtoMember(1)] 
  private int? AuthenticationMethodDataTransferField {
      get { return AuthenticationMethod == null ? (int?)null
                               : AuthenticationMethod.Value; }
      set { AuthenticationMethod = value == null ? null
                               : AuthenticationMethod.FromInt(value.Value); }
  }

  public AuthenticationMethod AuthenticationMethod { get; set; }
}

这避免了额外的字段和任何回调。 类似的事情也可以通过代理类型来完成,但以上应该适用于大多数简单的情况。

序列化枚举成员的机制非常简单:

[ProtoContract]
public class SomethingContainingAnAuthenticationMethod
{
    [ProtoMember(1)] 
    public AuthenticationMethod AuthenticationMethod { get; set; }
}

而且……就是这样。 有时的小问题(这可能会引发关于无法找到带值的枚举的错误)是隐式零行为,但这只是被避免的:

    [ProtoMember(1, IsRequired=true)] 
    public AuthenticationMethod AuthenticationMethod { get; set; }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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