C# 如何使用protobuf';C中有什么?
以下是我的protobuf的数据模型:C# 如何使用protobuf';C中有什么?,c#,protocol-buffers,C#,Protocol Buffers,以下是我的protobuf的数据模型: message GetNewsRespone{ repeated google.protobuf.Any instrument = 1; } message Issue{ int64 id = 1; string title = 2; } 以下是我尝试用数据填充的内容: GetNewsRespone res = new GetNewsRespone(); Issue issue = new Issue(); issue.id = 123;
message GetNewsRespone{
repeated google.protobuf.Any instrument = 1;
}
message Issue{
int64 id = 1;
string title = 2;
}
以下是我尝试用数据填充的内容:
GetNewsRespone res = new GetNewsRespone();
Issue issue = new Issue();
issue.id = 123;
layer.instrument .AddRange(???);
如何将
问题添加到我的GetNewsRespone.instrument
,这是一个任意数组?您可以在C#中使用任意类提供的方法。让我给你举个例子
假设我们有以下协议缓冲区:
syntax "proto3"
import "google/protobuf/any.proto"
message Stock {
// Stock-specific data
}
message Currency {
// Currency-specific data
}
message ChangeNotification {
int32 id = 1;
google.protobuf.Any instrument = 2;
}
在C#code.Any类中提供了设置字段、提取消息和检查类型的方法
public void FormatChangeNotification(ChangeNotification change)
{
if (change.Instrument.Is(Stock.Descriptor))
{
FormatStock(change.Instrument.Unpack<Stock>());
}
else if (change.Instrument.Is(Currency.Descriptor))
{
FormatCurrency(change.Instrument.Unpack<Currency>());
}
else
{
throw new ArgumentException("Unknown instrument type");
}
}
public void FormatChangeNotification(变更通知变更)
{
if(变更工具Is(库存描述符))
{
FormatStock(change.Instrument.Unpack());
}
否则,如果(兑换工具Is(货币描述符))
{
FormatCurrency(change.Instrument.Unpack());
}
其他的
{
抛出新的ArgumentException(“未知仪器类型”);
}
}
希望我能帮助您理解如何在自己的代码中实现它。使用Google.Protobuf.WellKnownTypes.Any.Pack
比如:
对于您的代码:
GetNewsRespone res = new GetNewsRespone();
Issue issue = new Issue();
issue.id = 123;
res.instrument = Google.Protobuf.WellKnownTypes.Any.Pack(issue);
我想插入仪器(google.protobuf.Any)数据,而不是解包。
GetNewsRespone res = new GetNewsRespone();
Issue issue = new Issue();
issue.id = 123;
res.instrument = Google.Protobuf.WellKnownTypes.Any.Pack(issue);