问题
protogen.exe
generates this pattern for a proto2
message field of type long
:
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; }
}
but as proto2
does not include a date-time type ( and protobuf-net
does not support proto3
which includes google.protobuf.Timestamp
) it's not clear how to represent DateTime
in manually coded C# proto object.
This is probably wrong :
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; }
}
What is the correct way to decorate DateTime
properties for use with protobuf-net
?
回答1:
It depends on what you want it to look like on the wire. If you want it to be a long
(delta into epoch), then : do that. For example:
[ProtoMember(...)] public long Foo {get;set;}
If you want it to be a long
on the wire and a DateTime
in your code: do that:
public DateTime Foo {get;set;}
[ProtoMember(...)] private long FooSerialized {
get { return DateTimeToLong(Foo); }
set { Foo = LongToDateTime(value); }
}
If you don't care and just want to store a DateTime
, do that:
[ProtoMember(...)] public DateTime Foo {get;set;}
回答2:
The Timestamp
type is now supported:
[global::ProtoBuf.ProtoMember(1, IsRequired = false, Name=@"When",
DataFormat = global::ProtoBuf.DataFormat.WellKnown)]
public DateTime When {get;set;}
来源:https://stackoverflow.com/questions/39671574/protobuf-net-how-to-represent-datetime-in-c