是否可以在Windows Phone 7/8上使用protobuf-net对不可变类型进行序列化/反序列化? [英] Is it possible to serialize/deserialize immutable types with protobuf-net on Windows Phone 7/8?
问题描述
是否可以在Windows Phone 7/8上使用protobuf-net序列化/反序列化类型?
我尝试了下面的代码,似乎不支持构造函数跳过(即UseConstructor = false),所以我创建了无参数构造函数,但反序列化失败,并出现尝试访问该方法失败:Wp7Tests.ImmutablePoint.set_X(System.Double )"
Is it possible to serialize/deserialize types with protobuf-net on Windows Phone 7/8?
I've tried the code below, it seems Constructor skipping isn't supported (i.e. UseConstructor = false) so I created a parameterless constructor but the deserialization fails with "Attempt to access the method failed: Wp7Tests.ImmutablePoint.set_X(System.Double)"
public class ImmutablePoint
{
public double X { get; private set; }
public double Y { get; private set; }
public ImmutablePoint() {}
public ImmutablePoint(double x, double y)
{
X = x;
Y = y;
}
}
public sub Test()
{
ImmutablePoint pt = new ImmutablePoint(1, 2);
var model = TypeModel.Create();
var ptType = model.Add(typeof(ImmutablePoint), false);
ptType.AddField(1, "X");
ptType.AddField(2, "Y");
IsolatedStorageFile store = IsolatedStorageFile.GetUserStoreForApplication();
using (var stream1 = new IsolatedStorageFileStream("test.bin", FileMode.Create, store))
{
try
{
model.Serialize(stream1, pt);
}
catch (Exception e)
{
Debugger.Break();
}
}
const double EPSILON = 0.001;
using (var stream1 = new IsolatedStorageFileStream("test.bin", FileMode.Open, store))
{
try
{
ImmutablePoint ptDeSer = (ImmutablePoint) model.Deserialize(stream1,null, typeof(ImmutablePoint));
Debug.Assert(Math.Abs(pt.X - ptDeSer.X) < EPSILON);
Debug.Assert(Math.Abs(pt.Y - ptDeSer.Y) < EPSILON);
}
catch (Exception e)
{
Debugger.Break();
}
}
}
推荐答案
您可以使用代理;这里我用属性装饰它,但是也可以手动配置它:
You can use a surrogate; here I'm decorating it with attributes, but it can be configured manually too:
[ProtoContract]
public class MutablePoint {
[ProtoMember(1)] public double X { get; set; }
[ProtoMember(2)] public double Y { get; set; }
public static implicit operator MutablePoint(ImmutablePoint value) {
return value == null ? null : new MutablePoint {X=value.X, Y=value.Y};
}
public static implicit operator ImmutablePoint(MutablePoint value) {
return value == null ? null : new ImmutablePoint(value.X, value.Y);
}
}
,然后告诉模型在看到ImmutablePoint
时使用它:
and then tell the model to use this whenever it sees ImmutablePoint
:
var model = TypeModel.Create();
model.Add(typeof(MutablePoint), true);
model.Add(typeof(ImmutablePoint), false).SetSurrogate(typeof(MutablePoint));
序列化程序将根据需要使用运算符在它们之间进行切换.序列化程序将使用implicit
或explicit
自定义转换运算符.
The serializer will use the operators to switch between them as necessary. The serializer will use either implicit
or explicit
custom conversion operators.
像这样反序列化
ImmutablePoint ptDeSer = (ImmutablePoint)model.Deserialize(stream1, null, typeof(ImmutablePoint));
这篇关于是否可以在Windows Phone 7/8上使用protobuf-net对不可变类型进行序列化/反序列化?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!