3
我試圖支持MessagePack協議,我目前Servicestack實現。我需要它來支持(反)序列這樣定義ISegment的列表:使用MsgPack與Servicestack:我怎麼KnownType?
[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。它是如何完成的?
我不再能夠測試這個答案,但它看起來不錯。 – Brannon
這將拋出,如果你的任何執行類型是抽象的。增加一個額外的條件來篩選出來可修復:'。凡(!噸=> t.IsAbstract);' – Cocowalla