How to use protobuf-net extensions?

I created a .proto file, and ProtoBufTool successfully created a .cs file. I am new to csharp and I am trying to set extension fields. But do not know how to do this? Does anyone have examples of using extensions using protobuf-net.

My .proto file:

package messages; message DMsg { optional int32 msgtype = 1; extensions 100 to max; } extend DMsg { optional string fltColumns = 101; } 

Here is the class created:

 //------------------------------------------------------------------------------ // // 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); } } } 
+4
source share
1 answer

protobuf-net does not have brilliant extension support; you need to use field numbers (I don’t think it is doing anything with fltColumns at the moment). However, to get the values, you have to use Extensible.GetValue<T> / TryGetValue<T> (note self: make these extension methods in C # 3.0). To set the value, use AppendValue<T> - it cannot know whether it is a single value or a list ( repeated ), therefore the same API processes both scripts.

It is possible that the Jon version (much closer to the Java version) has better support here.

Example (I use handwritten classes for brevity, but it should also work with generated types):

  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 (ie 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; } } 
+6
source

Source: https://habr.com/ru/post/1300568/


All Articles