如果你在一個無害鏈中有兩個(或更多)類(在這種情況下GeoCoordinate繼承自PointF2D),你如何正確使用代理來允許兩種類型的序列化?如何序列化繼承鏈中的類型與protobuf-net代理?
舉個例子,我有這兩個代理類
public class SerializablePointF2D
{
[ProtoMember(1)]
public double[] Values { get; set; }
public static implicit operator SerializablePointF2D(PointF2D value)
{
return value == null ? null : new SerializablePointF2D {Values = value.ToArrayCopy()} ;
}`enter code here`
public static implicit operator PointF2D(SerializablePointF2D value)
{
return value == null ? null : new PointF2D(value.Values);
}
}
[ProtoContract]
public class SerializableGeoCoordinate {
[ProtoMember(1)]
public double[] Values { get; set; }
public static implicit operator SerializableGeoCoordinate(GeoCoordinate value)
{
return value == null ? null : new SerializableGeoCoordinate { Values = value.ToArrayCopy() };
}
public static implicit operator GeoCoordinate(SerializableGeoCoordinate value)
{
return value == null ? null : new GeoCoordinate(value.Values);
}
}
而這個代碼建立模型
var model = TypeModel.Create();
//GeoCoordinate
model.Add(typeof(PrimitiveSimpleF2D), false).AddSubType(1, typeof(PointF2D));
model.Add(typeof(PointF2D), false).AddSubType(4, typeof(GeoCoordinate)).SetSurrogate(typeof(SerializablePointF2D));
model.Add(typeof(GeoCoordinate), false).SetSurrogate(typeof(SerializableGeoCoordinate));
當我試圖序列這一點,被序列化作爲PointF2D而不是會有地理座標。我試着訂購我能想到 編輯的每個組合:基於Marc的代碼 下面我試圖
[ProtoContract]
public class SerializablePointF2D
{
[ProtoMember(1)]
public double[] Values { get; set; }
public static implicit operator SerializablePointF2D(PointF2D value)
{
if (value == null) return null;
var geoCoordinate = value as GeoCoordinate;
if (geoCoordinate != null) return new SerializableGeoCoordinate
{
Values = geoCoordinate.ToArrayCopy(),
};
return new SerializablePointF2D {Values = value.ToArrayCopy()};
}
public static implicit operator PointF2D(SerializablePointF2D value)
{
return value == null ? null : new PointF2D(value.Values);
}
}
[ProtoContract]
public class SerializableGeoCoordinate:SerializablePointF2D
{
}
而且我認爲他看起來正確的。它失敗了
System.InvalidOperationException : Unexpected sub-type: OsmSharp.Serialization.OsmSharpSerializer+SerializableGeoCoordinate
我的兩個類是相同的數據,我將如何改變你的代碼,這些類工作(我嘗試失敗)。應該返回新的A {X = value.X};返回新的ASer {X = value.X}; ?? – 2013-04-26 21:28:26
@DavidHayes OOPS!是的,我的錯誤。另外:如果數據相同,您希望使用代理人的原因是什麼?你知道如果需要,protobuf-net可以序列化私有字段和邊界構造函數嗎?你*可以*直接配置原始類型直接序列化,即使它們沒有公開友好的API, – 2013-04-26 21:57:23
我將在WP7/8上運行它,所以IIRC私人領域的東西不適用於不完整特色框架 – 2013-04-26 22:00:43