如何在 C# 中使用 protobuf 的 Any?
How can I use protobuf's Any in C#?
这是我的 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;
layer.instrument .AddRange(???);
如何将 Issue
添加到我的 GetNewsRespone.instrument
,这是一个任意数组?
Any class 提供了可在 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.theAnyclass提供了设置字段、提取消息、检查类型的方法。
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");
}
}
希望我能帮助您了解如何在您自己的代码中实现它。
使用Google.Protobuf.WellKnownTypes.Any.Pack
喜欢:
var myValue = Google.Protobuf.WellKnownTypes.Any.Pack(new Stock());
您的代码:
GetNewsRespone res = new GetNewsRespone();
Issue issue = new Issue();
issue.id = 123;
res.instrument = Google.Protobuf.WellKnownTypes.Any.Pack(issue);
这是我的 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;
layer.instrument .AddRange(???);
如何将 Issue
添加到我的 GetNewsRespone.instrument
,这是一个任意数组?
Any class 提供了可在 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.theAnyclass提供了设置字段、提取消息、检查类型的方法。
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");
}
}
希望我能帮助您了解如何在您自己的代码中实现它。
使用Google.Protobuf.WellKnownTypes.Any.Pack
喜欢:
var myValue = Google.Protobuf.WellKnownTypes.Any.Pack(new Stock());
您的代码:
GetNewsRespone res = new GetNewsRespone();
Issue issue = new Issue();
issue.id = 123;
res.instrument = Google.Protobuf.WellKnownTypes.Any.Pack(issue);