在 protobuf-net 中发出值类型默认值的序列化

toA*_*ork 5 .net c# protobuf-net

在我的项目中,我不仅需要时间,还需要有关 UTC 偏移量的信息。因此我考虑使用DateTimeOffset类。

我没有做任何魔法,只是声明了struct包含shortfor offset 和longfor ticks (与 中相同DateTimeOffset) - 当然还定义了ProtoContractProtoMember属性。

但是:即使这个值没有初始化(两个字段都为零),线路上还有 2 个额外的字节(我用 a 进行了交叉检查class)!

我尝试继承DefaultValueAttribute并设置我的默认值 - 但也无济于事。

原因是 protobuf-net 检查按DefaultValueAttribute名称(在MetaType.ApplyDefaultBehaviour(bool isEnum, ProtoMemberAttribute normalizedAttribute))。

if ((attrib = GetAttribute(attribs, "System.ComponentModel.DefaultValueAttribute")) != null)
{
      object tmp;
      if(attrib.TryGet("Value", out tmp)) defaultValue = tmp;
}
Run Code Online (Sandbox Code Playgroud)

但即使我改变了这一点,我也会抱怨例外DefaultValueDecorator.Read(Compiler.CompilerContext ctx, Compiler.CodeLabel label)

 default:
      throw new NotSupportedException("Type cannot be represented as a default value: " 
                                     + expected.FullName);
Run Code Online (Sandbox Code Playgroud)

有谁知道这个限制的原因?

为什么不使用 default(T) 作为值类型?