ProtoBuff C#数据结构文件制作

百度搜索"ProtoBuff C#工具",下载编译好的工具集,当然的也可以自己去git上下载源码自己编译。

一、编写.proto文件,就是用来定义数据结构存储什么东西的。

package kongjian;//生成cs文件的命名空间
//import "other.proto";//可以引入其他的定义文件,两个结构其实可以分开两个文件的
message Item
{
	required int32 Type = 1;//required表示 必须
	optional int32 SubType = 2;//optional表示 可选
	required int32 num = 3;
}

message ItemList
{
	repeated Item item = 1;//表示数组,解析后为List
}

二、利用工具解析为中间文件(.protodesc)再解析为c#类脚本(.cs)

一个工具是protoc.exe,一个是protogen.exe,我的是进入到工具目录中操作的

blob.png

三、看看解析成的cs文件类容

namespace item
{
  [global::System.Serializable, global::ProtoBuf.ProtoContract(Name=@"Item")]
  public partial class Item : global::ProtoBuf.IExtensible
  {
    public Item() {}
    
    private int _Type;
    [global::ProtoBuf.ProtoMember(1, IsRequired = true, Name=@"Type", DataFormat = global::ProtoBuf.DataFormat.TwosComplement)]
    public int Type
    {
      get { return _Type; }
      set { _Type = value; }
    }
    private int _SubType = default(int);
    [global::ProtoBuf.ProtoMember(2, IsRequired = false, Name=@"SubType", DataFormat = global::ProtoBuf.DataFormat.TwosComplement)]
    [global::System.ComponentModel.DefaultValue(default(int))]
    public int SubType
    {
      get { return _SubType; }
      set { _SubType = value; }
    }
    private int _num;
    [global::ProtoBuf.ProtoMember(3, IsRequired = true, Name=@"num", DataFormat = global::ProtoBuf.DataFormat.TwosComplement)]
    public int num
    {
      get { return _num; }
      set { _num = value; }
    }
    private global::ProtoBuf.IExtension extensionObject;
    global::ProtoBuf.IExtension global::ProtoBuf.IExtensible.GetExtensionObject(bool createIfMissing)
      { return global::ProtoBuf.Extensible.GetExtensionObject(ref extensionObject, createIfMissing); }
  }
  
  [global::System.Serializable, global::ProtoBuf.ProtoContract(Name=@"ItemList")]
  public partial class ItemList : global::ProtoBuf.IExtensible
  {
    public ItemList() {}
    
    private readonly global::System.Collections.Generic.List<Item> _item = new global::System.Collections.Generic.List<Item>();
    [global::ProtoBuf.ProtoMember(1, Name=@"item", DataFormat = global::ProtoBuf.DataFormat.Default)]
    public global::System.Collections.Generic.List<Item> item
    {
      get { return _item; }
    }
  
    private global::ProtoBuf.IExtension extensionObject;
    global::ProtoBuf.IExtension global::ProtoBuf.IExtensible.GetExtensionObject(bool createIfMissing)
      { return global::ProtoBuf.Extensible.GetExtensionObject(ref extensionObject, createIfMissing); }
  }
  
}

四、同理的,利用同一个.proto文件,可以生成不同平台使用,但是数据结构对应上的客户端文件和服务端文件,这就方便了命令数据结构的对应了。


首页 我的博客
粤ICP备17103704号