ProtoBuf.Net - 使用Proto作为TypeFormatter

时间:2012-03-25 15:41:19

标签: .net protobuf-net

使用ProtoBuf.Net作为NetDataContractSerializer(或BinarySerializer)进行POC, 我在这里发布了代码code。 这是试验和错误,仍然不适用于List,Dictionary等。 看起来我走向了错误的方向, 这可行吗?

您的反馈将不胜感激。

1 个答案:

答案 0 :(得分:0)

我正在使用Protobuf.net,我通过标记我的类来做到这一点:

  namespace music
  {
      [ProtoContract]
      public class Album
      {
          [ProtoMember(1)]
          public string Name { get; set; }

          [ProtoMember(2)]
         public List<string> TrackList { get; set; }
      }
  }

这也适用于字典和列表。

相同的编号约定适用于使用.proto消息文件的属性,但您可以在基类上包含如下属性:

[ProtoContract]
[ProtoInclude(10, typeof(TypeInheritingFromPerson))]
[ProtoInclude(11, typeof(AnotherTypeInheritingFromPerson))]
public abstract class Person
{
    [DataMember]
    [ProtoMember(1)]
    public string Name { get; set; }
 ...

然后使用这行代码序列化:

  MemoryStream stream = new MemoryStream();
  ProtoBuf.Serializer.Serialize<Album>(stream, album);

您当然可以使用文件流而不是内存流:)

如果您正在使用WCF,您可以直接在配置文件中交换Protobuf序列化程序的DataContractSerializer(如从protobuf.net文档中粘贴的副本),因此您无需手动调用任何序列化代码: / p>

将以下内容添加到system.serviceModel部分中的服务器和客户端app.config:

           <behaviors>
           <endpointBehaviors>
             <behavior name="ProtoBufBehaviorConfig">
               <ProtoBufSerialization/>
             </behavior>
           </endpointBehaviors>
         </behaviors>
         <extensions>
           <behaviorExtensions>
             <add name="ProtoBufSerialization" type="ProtoBuf.ServiceModel.ProtoBehaviorExtension, protobuf-net, Version=1.0.0.255, Culture=neutral, PublicKeyToken=257b51d87d2e4d67"/>
           </behaviorExtensions>
         </extensions>

配置端点以具有behaviorConfiguration,如下所示:

         <service name="TK.Framework.Samples.ServiceModel.Contract.SampleService">
           <endpoint address="http://myhost:9003/SampleService" binding="basicHttpBinding" behaviorConfiguration="ProtoBufBehaviorConfig"
            bindingConfiguration="basicHttpBindingConfig" name="basicHttpProtoBuf" contract="ISampleServiceContract" />
         </service>
         <client>
             <endpoint address="http://myhost:9003/SampleService" binding="basicHttpBinding"
                 bindingConfiguration="basicHttpBindingConfig" contract="ISampleServiceContract"
                 name="BasicHttpProtoBufEndpoint" behaviorConfiguration="ProtoBufBehaviorConfig"/>
          </client>

我希望这对您有所帮助,但如果您有任何疑问,请告诉我,或者任何事情都不清楚:)