Map 這個結構對應 C# 的資料結構就是 Dictionary,今天就對這個結構介紹一下
message Student {
string name = 1;
string class = 2;
map<string, int32> scores = 3;
}
在 C# 端這邊跟前面介紹的 Repeated 不太一樣,可以初始化時直接 setter
Student student = new Student()
{
Name = "John Doe",
Class = "高中一甲",
// 不需要 new 直接宣告
Scores = { { "數學", 90 }, { "英文", 88 } }
};
// 新增 key/value 方式
student.Scores["國文"] = 85;
student.Scores.Add("自然", 60);
下面提一些限制,Key 不能是 float/double/byte/message 這幾種。使用時要注意一下
message Student {
string name = 1;
string class = 2;
map<StudendObj, int32> scores = 3;
}
// X 錯誤
message StudendObj {
int32 id = 1;
}