需要序列化包含DrawingBrush的一些BL结构。我把它重写如下:
[ProtoContract]
public class BaseProtoBuf : INotifyPropertyChanged, IFormattable
{
[ProtoMember(1)]
public string ID { get; set; }
// Bunch of properties of .net primitive types
// ..
private DrawingBrush _geometry;
[ProtoMember(9)]
[Browsable(false)]
public DrawingBrush Geometry
{
get { return _geometry; }
set
{
_geometry = value;
ScaleDrawing();
}
}
}
[ProtoContract]
[ProtoInclude(1, typeof(string))]
// All other includes
[ProtoInclude(9, typeof(DrawingBrush)]
public class DerivedProtoBuf : BaseProtoBuf, ICloneable
{
// Some additional properties of primitive types, annotated starting with ProtoMember 10 and so on
}
要序列化我正在执行以下代码:
const string fileName = "Protobuf.bin";
using (var file = File.Create(fileName))
{
file.Position = 0;
var testBase = new BaseProtoBuf
{
Height = 100,
Width = 100,
Name = "Test 1",
OffsetX = 200,
OffsetY = 200,
Geometry = sourceList[0].Geometry // some not-null DrawingBrush
};
Serializer.Serialize(file, testBase);
file.Position = 0;
var restored = Serializer.Deserialize<BaseProtoBuf>>(file);
}
}
我需要序列化Derived类对象,但在Base序列化期间,我得到“找不到合适的默认DrawingBrush编码”。认为这是因为对于某些对象,DrawingBrush可以为null,但在测试一中,它不是。正确序列化的任何变通方法1)基础对象与非null DrawingBrush 2)派生对象与null DrawingBrush?提前谢谢。
答案 0 :(得分:3)
更正用于序列化简单WPF刷的RuntimeTypeModel配置:
RuntimeTypeModel.Default.Add(typeof(Brush), false)
.AddSubType(300, typeof(SolidColorBrush));
RuntimeTypeModel.Default.Add(typeof(SolidColorBrush), false)
.Add("Color");
RuntimeTypeModel.Default.Add(typeof(Color), false)
.Add("A", "R", "G", "B"); // needed for proper color serialization
RuntimeTypeModel.Default.Add(typeof(SolidColorBrush), false)
.Add("Color");
RuntimeTypeModel.Default.Add(typeof(DrawingBrush), false)
.Add("Stretch", "Drawing");
RuntimeTypeModel.Default.Add(typeof(Drawing), false)
.AddSubType(100, typeof(DrawingGroup))
.AddSubType(200, typeof(GeometryDrawing));
RuntimeTypeModel.Default.Add(typeof(DrawingGroup), false)
.Add("Children");
RuntimeTypeModel.Default.Add(typeof(Pen), false)
.Add("Brush", "Thickness", "LineJoin");
RuntimeTypeModel.Default.Add(typeof(GeometryDrawing), false)
.Add("Brush", "Geometry", "Pen");
答案 1 :(得分:2)
由于未定义合约,DrawingBrush不会立即进行Serializable。各种选择: