没有属性的protobuf-net序列化

Mik*_*ike 14 c# protobuf-net

我有一个DataContracts的程序集,我需要为它生成.proto模式,以便能够与java系统交换数据.DataContracts代码可以更改,但我无法在其中添加[ProtoContract][ProtoMember]属性,因为它将导致protobuf-net程序集依赖性.我们在系统的C#部分中使用WCF,因此我们不希望在大多数不适用于Java系统的C#项目中依赖proto-buf程序集.

GettingStarted部分的protobuf-net网站上,它说:

不喜欢属性?
在v2中,可以通过RuntimeTypeModel在运行时配置可以使用属性完成的所有操作.

但是我不知道如何在没有属性的情况下实际配置序列化,我还没有看到任何这样的例子.

我正在努力做到

[DataContract]
public class MyEntity
{
    [DataMember(Order = 1)]
    public String PropertyA { get; set; }

    [DataMember(Order = 2)]
    public int PropertyB { get; set; }
}

RuntimeTypeModel.Default.Add(typeof(MyEntity), false);

string proto = Serializer.GetProto<MyEntity>();
Run Code Online (Sandbox Code Playgroud)

并获得以下值作为 proto

package ProtobufTest;

message MyEntity {
}
Run Code Online (Sandbox Code Playgroud)

Mar*_*ell 12

澄清:这个答案的大部分都与编辑前的问题有关,其中false传递给了RuntimeTypeModel.Add(...)


namespace ProtobufTest用r2.0.0.640(当前的NuGet部署)使用了你的确切代码(我推断这是在,但其余的是从问题中复制/粘贴),我得到:

package ProtobufTest;

message MyEntity {
   optional string PropertyA = 1;
   optional int32 PropertyB = 2 [default = 0];
}
Run Code Online (Sandbox Code Playgroud)

此外,即使您删除该行,您也会得到完全相同的结果RuntimeTypeModel.Default.Add(...).

我不清楚为什么你会看到不同的东西 - 你能澄清一下:

  • 这protobuf网版本使用的是完全相同
  • 如果那些[DataContract]/ [DataMember]属性是System.Runtime.Serialization.dll那些,或属于你自己(抱歉,如果这似乎是一个奇怪的问题)

要完全回答这个问题:如果你没有任何属性(并且你拥有的属性也很好),你也可以这样做:

RuntimeTypeModel.Default.Add(typeof(MyEntity), false)
    .Add(1, "PropertyA")
    .Add(2, "PropertyB");
Run Code Online (Sandbox Code Playgroud)

它将配置PropertyA为键1和PropertyB键2.