问题描述
||
鉴于:
public class E
{
public object Y { get; set; }
}
我正在尝试以下代码:
var m = RuntimeTypeModel.Default;
m.Add(typeof(E),false).Add(\"Y\");
// m.Add(typeof(object),false).AddSubType(1,typeof(int));
var e = new E { Y = 5 };
using (var ms = new MemoryStream())
{
m.Serialize(ms,e);
ms.Position = 0;
var e2 = (E)m.Deserialize(ms,null,typeof(E));
Debug.Assert(e.Y.Equals(e2.Y));
}
它失败并显示:
System.InvalidOperationException occurred
Message=No serializer defined for type: System.Object
Source=protobuf-net
StackTrace:
at ProtoBuf.Meta.ValueMember.GetCoreSerializer(Type type,WireType& defaultWireType,Boolean asReference,Boolean dynamicType) in C:\\Work\\protobuf-net-v2\\protobuf-net\\Meta\\ValueMember.cs:line 398
InnerException:
因此,我取消第三行的注释,但随后得到:
System.ArgumentException occurred
Message=Not valid for primitive types
Parameter name: type
Source=protobuf-net
ParamName=type
StackTrace:
at ProtoBuf.Meta.MetaType..ctor(RuntimeTypeModel model,Type type) in C:\\Work\\protobuf-net-v2\\protobuf-net\\Meta\\MetaType.cs:line 166
InnerException:
因此,问题是-我如何(反)序列化包含原始装箱值类型实例的对象属性?
请注意,相同的方法也适用于非原始值类型,例如DateTime(当然,我必须使用代理)。
编辑
如果我在方法ProtoBuf.Meta.MetaType.MetaType
中注释了本原性检查,那么以下代码可以正常工作:
static void Main()
{
var m = RuntimeTypeModel.Default;
m.Add(typeof(E),false).Add(\"Y\");
m.Add(typeof(object),typeof(int));
m.Add(typeof(IntSurrogate),false).Add(\"Value\");
m.Add(typeof(int),false).SetSurrogate(typeof(IntSurrogate));
var e = new E { Y = 5 };
using (var ms = new MemoryStream())
{
m.Serialize(ms,e);
ms.Position = 0;
var e2 = (E)m.Deserialize(ms,typeof(E));
Debug.Assert(e.Y.Equals(e2.Y));
}
}
internal class IntSurrogate
{
public static implicit operator int(IntSurrogate surrogate)
{
return surrogate.Value;
}
public static implicit operator IntSurrogate(int v)
{
return new IntSurrogate { Value = v };
}
internal int Value { get; set; }
}
当然,我希望无需IntSurrogate
即可使用它。
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)