是否可以在 Windows Phone 7/8 上使用 protobuf-net 序列化/反序列化类型?
我尝试了下面的代码,似乎不支持构造函数跳过(即 UseConstructor = false),因此我创建了一个无参数构造函数,但反序列化失败,并显示“尝试访问方法失败: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();
}
}
}
您可以使用代理人;这里我用属性来装饰它,但它也可以手动配置:
[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
:
var model = TypeModel.Create();
model.Add(typeof(MutablePoint), true);
model.Add(typeof(ImmutablePoint), false).SetSurrogate(typeof(MutablePoint));
序列化器将根据需要使用运算符在它们之间进行切换。序列化器将使用implicit
or explicit
自定义转换运算符。
编辑:
像这样反序列化
ImmutablePoint ptDeSer = (ImmutablePoint)model.Deserialize(stream1, null, typeof(ImmutablePoint));
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)