来源于
https://github.com/protobuf-net/protobuf-net
如果你需要对象的深拷贝,序列化,以及网络传输,可以考虑使用protobuf-net
关于protobuf-net的详细介绍可以参考其github地址。以下只是部分摘录
protobuf-net
protobuf-net is a contract based serializer for .NET code, that happens to write data in the “protocol buffers” serialization format engineered by Google. The API, however, is very different to Google’s, and follows typical .NET patterns (it is broadly comparable, in usage, to XmlSerializer, DataContractSerializer, etc). It should work for most .NET languages that write standard types and can use attributes.
Release Notes
Change history and pending changes are here.
To understand how protobuf-net relates to protobuf see here.
Supported Runtimes
- .NET Framework 4.6.1+
- .NET Standard 2.0+
Runtime Installation
All stable and some pre-release packages are available on NuGet. CI Builds are available via MyGet (feed URL: https://www.myget.org/F/protobuf-net/api/v3/index.json
).
You can use the following command in the Package Manager Console:
Install-Package protobuf-net
Basic usage
1 First Decorate your classes
[ProtoContract]
class Person {
[ProtoMember(1)]
public int Id {get;set;}
[ProtoMember(2)]
public string Name {get;set;}
[ProtoMember(3)]
public Address Address {get;set;}
}
[ProtoContract]
class Address {
[ProtoMember(1)]
public string Line1 {get;set;}
[ProtoMember(2)]
public string Line2 {get;set;}
}
Note that unlike XmlSerializer, the member-names are not encoded in the data - instead, you must pick an integer to identify each member. Additionally, to show intent it is necessary to show that we intend this type to be serialized (i.e. that it is a data contract).
2 Serialize your data
This writes a 32 byte file to “person.bin” :
var person = new Person {
Id = 12345, Name = "Fred",
Address = new Address {
Line1 = "Flat 1",
Line2 = "The Meadows"
}
};
using (var file = File.Create("person.bin")) {
Serializer.Serialize(file, person);
}
3 Deserialize your data
This reads the data back from “person.bin” :
Person newPerson;
using (var file = File.OpenRead("person.bin")) {
newPerson = Serializer.Deserialize<Person>(file);
}
Notes
Notes for Identifiers
- they must be positive integers (for best portability, they should be <= 536870911 and not in the range 19000-19999)
- they must be unique within a single type but the same numbers can be re-used in sub-types if inheritance is enabled
- the identifiers must not conflict with any inheritance identifiers (discussed later)
- lower numbers take less space - don’t start at 100,000,000
- the identifier is important; you can change the member-name, or shift it between a property and a field, but changing the identifier changes the data
Advanced subjects
Inheritance
Inheritance must be explicitly declared, in a similar way that if must for XmlSerializer and DataContractSerializer. This is done via [ProtoInclude(…)] on each type with known sub-types:
[ProtoContract]
[ProtoInclude(7, typeof(SomeDerivedType))]
class SomeBaseType {...}
[ProtoContract]
class SomeDerivedType {...}
There is no special significance in the 7 above; it is an integer key, just like every [ProtoMember(…)]. It must be unique in terms of SomeBaseType (no other [ProtoInclude(…)] or [ProtoMember(…)] in SomeBaseType can use 7), but does not need to be unique globally.
.proto file
As an alternative to writing your classes and decorating them, You can generate your types from a .proto schema using protogen;
the protogen tool is available as a zip from that location, or as a “global tool” (multi-platform).
Alternative to attributes
In v2+, everything that can be done with attributes can also be configured at runtime via RuntimeTypeModel. The Serializer.* methods are basically just shortcuts to RuntimeTypeModel.Default., so to manipulate the behaviour of Serializer., you must configure RuntimeTypeModel.Default.
Support
I try to be responsive to Stack Overflow questions in the protobuf-net tag, issues logged on GitHub, email, etc. I don’t currently offer a paid support channel. If I’ve helped you, feel free to buy me a coffee or see the “Sponsor” link at the top of the GitHub page.
Start Here
What is protobuf-net?
protobuf-net is a binary serialization engine, along similar lines to BinaryFormatter
but using the “protocol buffers” [PB] specification as laid out by Google.
The core protobuf-net library is a single dll; other projects are presented for
testing and example purposes.
Many PB implementations start with a .proto text file (describing the types), with
the developer running a command-line tool to generate code in their target
language. Deliberately, protobuf-net started the other way around: it is designed
to work with existing .NET types at runtime. This allows you to use your existing
data objects, but still with lots of optimisations to keep things very fast.
There is a C# code generation version (courtesy of Jon Skeet), and a proposed future
extension is to allow generation of protobuf-net classes from a .proto file.
How do I use it?
These steps are a walkthrough of the QuickStart project.
0: add a reference to protobuf-net
protobuf-net is a runtime engine, and the assembly is required (and should be
deployed with your program).
1: define your data objects (“1 Data Objects.cs”)
protobuf-net uses regular .NET classes. The only requirement (in common with
other serializers such as XmlSerializer) is that there must be a public
parameterless constructor, and it must be marked for serialization.
Any properties you want to serialize must have a “getter” and “setter”,
and an integer “tag” is required on each (used to uniquely identify each
property when serialized). Collection properties can also be serialized, but
it is not necessary to have a “setter”, as items can be added to the
existing list.
2: write objects to a file and read them back (“2 File Access.cs”)
This sample shows writing object-graphs to simple streams such as FileStream,
using the Serialize and Deserialize methods.
3: write objects to a socket and read them back (“3 Sockets.cs”)
Network IO is more complicated, especially since we can reasonably expect
a conversation between client and server on the same connection, but each
needs to know how much data is part of the current request/response. This
sample shows using the SerializeWithLengthPrefix/DeserializeWithLengthPrefix
methods to communicate over a socket.