我试图用 protobuf-net序列化一些对象,但不幸的是他们自由地使用了Datebuff-netset,而且还没有被protobuf-net支持。这导致很多: No serializer defined for type: System.DateTimeOffset 我可以为未知类型
No serializer defined for type: System.DateTimeOffset
我可以为未知类型定义自己的序列化例程吗? (same question早些时候被问到,但他的问题已经解决了。)
我正在使用最新的protobuf-net beta,v2.0.0.431,在.NET 4下,如果重要。我也使用运行时定义,所以我没有办法声明性地指定如何处理某些属性。
有两种方法来处理未知的“常见”类型的问题;第一个是使用垫片属性,例如将值代表类似的属性(例如字符串或长例):[ProtoMember(8)]
public string Foo {
get { ... read from the other member ... }
set { ... assign the other member ... }
}
另一种方法是代理,这是一个自动替代的第二个protobuf合同。使用替代品的要求是:
>这两种类型之间必须有一个定义的转换操作符(implicit或Explicit)(例如DateTimeOffset和DateTimeOffsetSurrogate)
>然后使用SetSurrogate(代理类型)来教育protobuf-net,例如RuntimeTypeModel.Default.Add(typeof(DateTimeOffset),false).SetSurrogate(typeof(DateTimeOffsetSurrogate));
垫片属性更简单,但需要重复每个成员。代理将自动应用于模型中所有类型的实例。代理遵循标准的protobuf-net规则,所以你会指出哪些成员序列化等。
编辑:添加代码示例
using System;
using ProtoBuf;
[ProtoContract]
public class DateTimeOffsetSurrogate
{
[ProtoMember(1)]
public string DateTimeString { get; set; }
public static implicit operator DateTimeOffsetSurrogate(DateTimeOffset value)
{
return new DateTimeOffsetSurrogate {DateTimeString = value.ToString("u")};
}
public static implicit operator DateTimeOffset(DateTimeOffsetSurrogate value)
{
return DateTimeOffset.Parse(value.DateTimeString);
}
}
然后这样注册
RuntimeTypeModel.Default.Add(typeof(DateTimeOffset), false).SetSurrogate(typeof(DateTimeOffsetSurrogate));
