protobuf-net简单使用

  • 第一个测试的proto文件
 1 syntax = "proto3";
 2 package ProtoMsg;
 3 
 4 message Foo
 5 {
 6     string name = 1;
 7     int32 id = 2;
 8     repeated bytes data = 3;
 9     enum Types
10     {
11         Hight = 0;
12         Low = 1;
13         Normal = 2;
14     }
15     Types type = 4;
16 }
  •  第二个测试proto文件
1 syntax = "proto3";
2 import "Foo.proto";
3 package ProtoMsg;
4 
5 message FooWapper
6 {
7     repeated Foo foos = 1;
8 }
  • 分别生成C#源文件
1 protogen.exe Foo.proto --csharp_out=./
2 protogen.exe FooWrapper.proto --csharp_out=./
  • 例子程序
 1 static void Main(string[] args)
 2         {
 3             FooWapper fw = new FooWapper();
 4             Foo f = new Foo();
 5             f.Datas.Add(new byte[] {0x1, 0x2, 0x3});
 6             f.Id = 12345678;
 7             f.Name = "proto-net";
 8             f.Type = Foo.Types.Hight;
 9             fw.Foos.Add(f);
10 
11             byte[] data;
12             Console.WriteLine("开始序列化数据.");
13             using (var stream = new MemoryStream())
14             {
15                 Serializer.Serialize(stream, fw);
16                 data = stream.ToArray();
17             }
18 
19             Console.WriteLine("开始反序列化数据.");
20             using (var stream = new MemoryStream(data))
21             {
22                 var _fw = Serializer.Deserialize<FooWapper>(stream);
23                 Console.WriteLine(_fw);
24             }
25 
26             Console.ReadKey();
27         }
  • 程序执行结果

 

posted @ 2017-11-27 02:19  非法关键字  阅读(2813)  评论(3编辑  收藏  举报