假設有一個proto message定義如下:
message Example {
optional bool a = 1;
optional bool b = 2;
};
如果想在代碼裏知道a這個field定義時的給的序號是多少(這裏是1):
Example obj;
std::cout << obj.GetDescriptor()->FindFieldByName("a")->number() << std::endl;
// output: 1
如果沒有名字爲a的字段,obj.GetDescriptor()->FindFieldByName("a")的結果是一個空指針。
如果想知道序號1對應的field的name:
Example obj;
std::cout << obj.GetDescriptor()->FindFieldByNumber(1)->name() << std::endl;
// output: a
如果沒有序號爲1的字段,obj.GetDescriptor()->FindFieldByNumber(1)的結果是一個空指針。