例如,我想序列化和反序列化System.Drawing.Font
不可变且无法更改以适应 protobuf-net 约定的序列化和反序列化。一般来说,是否可以在 protobuf-net 中编写某种“自定义”序列化程序?
编辑:根据接受的答案,以下是代理的示例System.Drawing
:
[ProtoContract]
struct ProtoColor
{
[ProtoMember(1, DataFormat=DataFormat.FixedSize)]
public uint argb;
public static implicit operator Color(ProtoColor c)
{ return Color.FromArgb((int)c.argb); }
public static implicit operator ProtoColor(Color c)
{ return new ProtoColor { argb = (uint)c.ToArgb() }; }
}
[ProtoContract()]
class ProtoFont
{
[ProtoMember(1)]
string FontFamily;
[ProtoMember(2)]
float SizeInPoints;
[ProtoMember(3)]
FontStyle Style;
public static implicit operator Font(ProtoFont f) {
return new Font(f.FontFamily, f.SizeInPoints, f.Style);
}
public static implicit operator ProtoFont(Font f) {
return f == null ? null : new ProtoFont {
FontFamily = f.FontFamily.Name,
SizeInPoints = f.SizeInPoints,
Style = f.Style };
}
}
[ProtoContract()]
class ProtoStringFormat
{
[ProtoMember(1, DataFormat=DataFormat.Group)]
StringAlignment Alignment;
[ProtoMember(2)]
StringAlignment LineAlignment;
[ProtoMember(3)]
StringFormatFlags Flags;
public static implicit operator StringFormat(ProtoStringFormat f) {
return new StringFormat(f.Flags) { Alignment = f.Alignment,
LineAlignment = f.LineAlignment };
}
public static implicit operator ProtoStringFormat(StringFormat f) {
return f == null ? null : new ProtoStringFormat() {
Flags = f.FormatFlags, Alignment = f.Alignment,
LineAlignment = f.LineAlignment };
}
}
// Before serializing or deserializing...
static RuntimeTypeModel Model;
static StaticConstructor()
{
Model = TypeModel.Create();
Model.AllowParseableTypes=true;
Model.Add(typeof(Color), false).SetSurrogate(typeof(ProtoColor));
Model.Add(typeof(Font), false).SetSurrogate(typeof(ProtoFont));
Model.Add(typeof(StringFormat), false)
.SetSurrogate(typeof(ProtoStringFormat));
Model.Add(typeof(PointF), true).Add("X", "Y");
}