protobuf-net:如何在 C# 中表示 DateTime?

protobuf-net : how to represent DateTime in C#?

protogen.exelong 类型的 proto2 消息字段生成此模式:

private long _Count = default(long);
[global::ProtoBuf.ProtoMember(1, IsRequired = false, Name=@"Count", DataFormat = global::ProtoBuf.DataFormat.TwosComplement)]
[global::System.ComponentModel.DefaultValue(default(long))]
public long Count
{
  get { return _Count; }
  set { _Count = value; }
}

但由于 proto2 不包括日期时间类型(并且 protobuf-net 不支持 proto3 其中包括 google.protobuf.Timestamp ),不清楚如何表示 DateTime 在手动编码的 C# 原型对象中。

这可能是错误的:

private DateTime _When = DateTime.MinValue;
[global::ProtoBuf.ProtoMember(1, IsRequired = false, Name=@"When", DataFormat = global::ProtoBuf.DataFormat.Default)]
[global::System.ComponentModel.DefaultValue(DateTime.MinValue)]
public DateTime When
{
  get { return _When; }
  set { _When = value; }
}

修饰 DateTime 属性以供 protobuf-net 使用的正确方法是什么?

这取决于你希望它在电线上的样子。如果你想让它成为一个 long (进入纪元的增量),那么:这样做。例如:

[ProtoMember(...)] public long Foo {get;set;}

如果您希望它在网络上是 long 而在您的代码中是 DateTime:这样做:

 public DateTime Foo {get;set;}
 [ProtoMember(...)] private long FooSerialized {
    get { return DateTimeToLong(Foo); }
    set { Foo = LongToDateTime(value); }
  }

如果您不关心并且只想存储 DateTime,请执行此操作:

[ProtoMember(...)] public DateTime Foo {get;set;}

现在支持 Timestamp 类型:

[global::ProtoBuf.ProtoMember(1, IsRequired = false, Name=@"When",
    DataFormat = global::ProtoBuf.DataFormat.WellKnown)]
public DateTime When {get;set;}