序列化动态类型参数 Protobuf-net [英] Serializing dynamic type parameter Protobuf-net
问题描述
我正在尝试使用 protobuf-net (2.0.0.668) 使用 params
对象数组序列化一个类.
I am trying to serialize a class with a params
object array using protobuf-net (2.0.0.668).
我的 params 对象[] 中可以有不同的类型.
There can be different types in my params object[].
使用 DataContractSerializer 时,只需使用 [KnownType]
就可以正常工作.
When using DataContractSerializer, simply using [KnownType]
works like expected.
我知道 protobuf-net 不是这种情况,我必须使用 [ProtoInclude]
和 DynamicType = true
代替,如下所示:
I understand that it isn't the case for protobuf-net, and that I must use [ProtoInclude]
instead, along with DynamicType = true
, like so:
[ProtoContract, ProtoInclude(20, typeof(Int32))] //Int32 as an example
public class MyParams
{
public MyParams(){}
public MyParams(
string name,
params object[] parms)
{
this.Name = name;
this.Parms = parms;
}
[ProtoMember(1)]
public string Name { get; set; }
[ProtoMember(2, DynamicType = true)]
public object[] Parms { get; set; }
}
奇怪的是,每当我在对象数组中传递一些字符串时,这项工作就会起作用,但如果我给它其他任何东西(在本例中为 Int32),它就会失败.
Strangely this work whenever I pass some strings in the object array but it fails if I give it anything else (Int32 in this example).
这是它抛出的异常:
Exception:Thrown: "Dynamic type is not a contract-type: Int32 (System.InvalidOperationException)
我错过了什么?
谢谢!
推荐答案
Dynamic type
的当前实现不支持原语.它只支持合约类型(其他类以某种方式定义为 ProtoContract
).
The current implementation of Dynamic type
does not support primitives. It only supports contract types (other classes which have are somehow defined as ProtoContract
).
来自维基:
DynamicType - 存储带有类型的附加类型信息(默认情况下它包括 AssemblyQualifiedName,尽管这可以由用户控制).这使得序列化弱模型成为可能,即对象用于属性成员,但是目前这仅限于契约类型(不是基元),并且不适用于具有继承的类型(这些限制可能会在以后删除).与 AsReference 一样,它使用了非常不同的布局格式
DynamicType - stores additional Type information with the type (by default it includes the AssemblyQualifiedName, although this can be controlled by the user). This makes it possible to serialize weak models, i.e. where object is used for property members, however currently this is limited to contract types (not primitives), and does not work for types with inheritance (these limitations may be removed at a later time). Like with AsReference, this uses a very different layout format
这篇关于序列化动态类型参数 Protobuf-net的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!