如果您在 ineritance 链中有两个(或更多)类(在这种情况下 GeoCoordinate 继承自 PointF2D),您如何正确使用代理项来允许任一类型的序列化?
例如,我有这两个代理类
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 而不是 GeoCoordinate。我已经尝试了我能想到的所有排序组合编辑:基于下面的 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