gpt4 book ai didi

c# - 序列化动态类型参数 Protobuf-net

转载 作者:行者123 更新时间:2023-11-30 22:10:23 26 4
gpt4 key购买 nike

没有答案的可能重复项:herehere .

我正在尝试使用 protobuf-net (2.0.0.668) 使用 params 对象数组序列化一个类。

我的 params object[] 中可以有不同的类型。

当使用 DataContractSerializer 时,只需使用 [KnownType] 就可以像预期的那样工作。

我知道 protobuf-net 不是这种情况,我必须改用 [ProtoInclude] 以及 DynamicType = true,如下所示:

[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),它就会失败。

这是它抛出的异常:

Exception:Thrown: "Dynamic type is not a contract-type: Int32 (System.InvalidOperationException)

我错过了什么?

谢谢!

最佳答案

动态类型 的当前实现不支持原语。它仅支持契约类型(其他类以某种方式定义为 ProtoContract)。

来自 the wiki :

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

关于c# - 序列化动态类型参数 Protobuf-net,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20848605/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com