[英]c# protobuf reflection usage
I am using official c# protobuf(not Protobuf-net). 我正在使用官方的C#protobuf(不是Protobuf-net)。 Dose it support create a message object according to its type? 是否支持根据其类型创建消息对象?
The typical deserialize is like: 典型的反序列化是:
MyProtoMessageClass obj = MyProtoMessageClass.Parser.ParseFrom(byteArray);
But how to generate the instance according to a string which is 但是如何根据字符串生成实例
"MyProtoMessageClass"
or a obj of Google.Protobuf.Reflection.MessageDescriptor
which is 或Google.Protobuf.Reflection.MessageDescriptor
的obj
MyProtoMessageClass.Descriptor
? ?
UPDATE UPDATE
delegate void handler(object data);
class Wrapper
{
public handler h;
public global::Google.Protobuf.IMessage m;
}
Dictionary<ushort, Wrapper> dict = new Dictionary<ushort, Wrapper>();
// register
class HandlerClass {
public void handle(object o) {
ProtoMessageClass data = (ProtoMessageClass)o;
// use data
}
}
h = HandlerClassObj.handle;
m = new ProtoMessageClass();
dict[1] = new Wrapper{h = h, m = m};
// call
ushort cmd = 1;// from socket
byte[] dataRecv; // from socket
var w = dict[cmd];
Google.Protobuf.IMessage msg = w.m.Descriptor.Parser.ParseFrom(dataRecv);
w.h.Invoke(msg);
Assume we got this proto definition: 假设我们得到了这个原始定义:
syntax = "proto3";
package tutorial;
option csharp_namespace = "T1.Models";
message Person {
int32 id = 1;
string name = 2;
}
Compiling this proto file, we get a class called Person
that implements Google.Protobuf.IMessage
. 编译此原始文件,我们得到一个名为Person
的类,该类实现了Google.Protobuf.IMessage
。 This interface contains a property MessageDescriptor Descriptor { get; }
此接口包含MessageDescriptor Descriptor { get; }
属性MessageDescriptor Descriptor { get; }
MessageDescriptor Descriptor { get; }
, which is implemented by the class Person
and returns a public static property of type MessageDescriptor
. MessageDescriptor Descriptor { get; }
,由Person
类实现,并返回MessageDescriptor
类型的公共静态属性。
The MessageDescriptor
contains a public static property called Parser
, and we can call the ParseFrom(byteArray)
of this. MessageDescriptor
包含一个称为Parser
的公共静态属性,我们可以调用其的ParseFrom(byteArray)
。
the code: 编码:
var typ = Assembly.GetExecutingAssembly().GetTypes().First(t => t.Name == "Person"); //get the type using the string we got, here it is 'Person'
var descriptor = (MessageDescriptor)typ.GetProperty("Descriptor", BindingFlags.Public | BindingFlags.Static).GetValue(null, null); // get the static property Descriptor
var person = descriptor.Parser.ParseFrom(byteArray); // parse the byte array to Person
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.