如何使用protobuf-net扩展?

VNa*_*haM 4 c# protobuf-net

我创建了一个.proto文件,并且ProtoBufTool成功创建了.cs文件.我是csharp的新手,我正在尝试设置扩展字段.但不知道怎么做?有没有人有任何使用protobuf-net使用扩展的例子.

我的.proto文件:

package messages;
message DMsg 
{
    optional int32 msgtype = 1;
    extensions 100 to max;
}
extend DMsg
{
optional string fltColumns = 101;
}
Run Code Online (Sandbox Code Playgroud)

这是创建的类:

//------------------------------------------------------------------------------
// 
//     This code was generated by a tool.
//
//     Changes to this file may cause incorrect behavior and will be lost if
//     the code is regenerated.
// 
//------------------------------------------------------------------------------

// Generated from: message.proto
namespace messages
{
[global::System.Serializable, global::ProtoBuf.ProtoContract(Name=@"DMsg")]
public partial class DMsg : global::ProtoBuf.IExtensible
{
  public DMsg() {}


private int _msgtype = default(int);
[global::ProtoBuf.ProtoMember(1, IsRequired = false, Name=@"msgtype", DataFormat = global::ProtoBuf.DataFormat.TwosComplement)][global::System.ComponentModel.DefaultValue(default(int))]
public int msgtype
{
  get { return _msgtype; }
  set { _msgtype = value; }
}
  private global::ProtoBuf.IExtension extensionObject;
  global::ProtoBuf.IExtension global::ProtoBuf.IExtensible.GetExtensionObject(bool createIfMissing)
    { return global::ProtoBuf.Extensible.GetExtensionObject(ref extensionObject, createIfMissing); }
}

}
Run Code Online (Sandbox Code Playgroud)

Mar*_*ell 6

protobuf-net 对扩展没有很好的支持; 你需要使用字段编号(我不认为它现在做任何事情fltColumns).但是,要获得值,您应该能够使用Extensible.GetValue<T>/ TryGetValue<T>(注意自己:在C#3.0中使用这些扩展方法).要设置值使用AppendValue<T>- 它无法知道这是单值还是列表(repeated),因此相同的API会处理这两种情况.

这可能是乔恩的版本(即更接近Java版本)在这里有更好的支持.

示例(我为了简洁起见使用手写类,但它也应该与生成的类型一起使用):

    static void Main()
    {
        MyData data = new MyData();
        data.Id = 123;
        // something we know only by field id...
        Extensible.AppendValue<string>(data, 27, "my name");
        string myName = Extensible.GetValue<string>(data, 27);

        // this should be OK too (i.e. if we loaded it into something that
        // *did* understand that 27 means Name)
        MyKnownData known = Serializer.ChangeType<MyData, MyKnownData>(data);
        Console.WriteLine(known.Id);
        Console.WriteLine(known.Name);
    }

    [ProtoContract]
    class MyData : Extensible
    {
        [ProtoMember(1)]
        public int Id { get; set; }
    }

    [ProtoContract]
    class MyKnownData
    {
        [ProtoMember(1)]
        public int Id { get; set; }
        [ProtoMember(27)]
        public string Name{ get; set; }
    }
Run Code Online (Sandbox Code Playgroud)