我正在尝试在我当前的 Servicestack 实现中支持 MessagePack 协议。我需要它来支持(反)序列化这样定义的 ISegment 列表:
[KnownType(typeof(ArcSegment)), KnownType(typeof(LineSegment))]
public class PathRequest
{
public List<ISegment> Segments {get;set;}
}
public interface ISegment
{
Point StartPoint {get;set;}
Point EndPoint {get;set;}
}
public class ArcSegment: ISegment {...}
public class LineSegment: ISegment {...}
开箱即用它告诉我
类型“Asi.Geometry.ISegment”没有默认(无参数)公共构造函数和具有 Int32 参数的公共构造函数。
这是非常真实的。显然它不使用 KnownType 属性。在网上阅读后,我发现我可以制作自己的序列化器。因此我尝试了这个:
class ArcLineSerializer: MessagePackSerializer<ISegment>
{
private readonly MessagePackSerializer<ArcSegment> _arcSerializer = MessagePackSerializer.Create<ArcSegment>();
private readonly MessagePackSerializer<LineSegment> _lineSerializer = MessagePackSerializer.Create<LineSegment>();
protected override void PackToCore(Packer packer, ISegment objectTree)
{
if(objectTree is ArcSegment)
_arcSerializer.PackTo(packer, (ArcSegment)objectTree);
else if (objectTree is LineSegment)
_lineSerializer.PackTo(packer, (LineSegment)objectTree);
else
throw new NotSupportedException();
}
protected override ISegment UnpackFromCore(Unpacker unpacker)
{
var data = unpacker.Data;
if (data != null)
{
if (data.Value.IsTypeOf<ArcSegment>().GetValueOrDefault())
return _arcSerializer.UnpackFrom(unpacker);
if (data.Value.IsTypeOf<LineSegment>().GetValueOrDefault())
return _lineSerializer.UnpackFrom(unpacker);
throw new NotSupportedException();
}
return null;
}
}
唉,这给了我尝试构造 _arcSerializer 的相同错误。它是怎么做的?