我正在使用 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,您可以像这样直接在配置文件中将 DataContractSerializer 替换为 Protobuf 序列化程序(从 protobuf.net 文档中复制粘贴),因此您无需手动调用任何序列化代码:
将以下内容添加到服务器和客户端 app.config 的 system.serviceModel 部分:
<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>
将您的端点配置为具有如下行为配置:
<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>
我希望这对您有所帮助,但如果您有任何问题或不清楚的地方,请告诉我:)