iT邦幫忙

2025 iThome 鐵人賽

DAY 16
1
Software Development

30 天的 .Net gRPC 迷途系列 第 16

Day16 gRPC 進階屬性格式(Map)

  • 分享至 

  • xImage
  •  

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;
}

上一篇
Day15 gRPC 進階屬性格式(陣列 Repeated)
下一篇
Day17 gRPC 進階屬性格式(Oneof)
系列文
30 天的 .Net gRPC 迷途20
圖片
  熱門推薦
圖片
{{ item.channelVendor }} | {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言