假设我想序列化,然后使用 protobuf-net 反序列化一个小数:
const decimal originalDecimal = 1.6641007661819458m;
using (var memoryStream = new MemoryStream())
{
Serializer.Serialize(memoryStream, originalDecimal);
memoryStream.Position = 0;
var deserializedDecimal = Serializer.Deserialize<decimal>(memoryStream);
Assert.AreEqual(originalDecimal, deserializedDecimal);
}
它工作正常。Protobuf-net 在内部使用以下小数表示(参见Bcl.proto):
message Decimal {
optional uint64 lo = 1; // the first 64 bits of the underlying value
optional uint32 hi = 2; // the last 32 bis of the underlying value
optional sint32 signScale = 3; // the number of decimal digits, and the sign
}
现在假设我通过代码定义了一个假定等效的原型合同:
[ProtoContract]
public class MyDecimal
{
[ProtoMember(1, IsRequired = false)]
public ulong Lo;
[ProtoMember(2, IsRequired = false)]
public uint Hi;
[ProtoMember(3, IsRequired = false)]
public int SignScale;
}
...然后我无法序列化 adecimal
并获得MyDecimal
回报,也无法序列化 aMyDecimal
并获得decimal
回报。
从decimal
到MyDecimal
:
const decimal originalDecimal = 1.6641007661819458m;
using (var memoryStream = new MemoryStream())
{
Serializer.Serialize(memoryStream, originalDecimal);
memoryStream.Position = 0;
// following line throws a Invalid wire-type ProtoException
Serializer.Deserialize<MyDecimal>(memoryStream);
}
从MyDecimal
到decimal
:
var myDecimal = new MyDecimal
{
Lo = 0x003b1ee886632642,
Hi = 0x00000000,
SignScale = 0x00000020,
};
using (var memoryStream = new MemoryStream())
{
Serializer.Serialize(memoryStream, myDecimal);
memoryStream.Position = 0;
// following line throws a Invalid wire-type ProtoException
Serializer.Deserialize<decimal>(memoryStream);
}
我在这里错过了什么吗?
我正在开发一个 C++ 应用程序,该应用程序需要通过协议缓冲区与 C# 进行通信,并且无法弄清楚十进制反序列化失败的原因。