【发布时间】:2021-04-18 06:46:30
【问题描述】:
我在 .Net Core 3.1 中使用 C#。我有一个类,用于现有项目/其他 API:
/// <summary>Class representing a Result Set (data coming from a result page,
/// plus the total count of the records coming from all the resulting pages) </summary>
/// <typeparam name="T">The class type of the result set</typeparam>
public class PagedResult<T>
{
/// <summary> Total number of rows in the result set </summary>
public long TotalRows { get; set; }
/// <summary> IList containing the data of the requested page's result set </summary>
public IList<T> PageData { get; set; } = new List<T>();
}
我将它用作许多消息的返回类型(基本上是每个分页查询)。
如何在 gRPC / Protobuf 中替换类似的内容?
我可以想到以下几点:
message PagedResult
{
int32 total_rows = 1;
repeated google.protobuf.Any page_data = 2;
}
但这将要求我将每个结果都视为不同。
另一种方法是为每个 page_data 类型创建一条新消息:
message MyEntityPagedResult
{
int32 total_rows = 1;
repeated MyEntity page_data = 2;
}
我知道 protobuf 不支持继承,但是有没有办法管理这种响应而不在 proto 中插入大量样板?有什么建议吗?
谢谢!
【问题讨论】:
-
你可以考虑使用protobuf.net,我认为处理泛型和继承就好了。我没有用gRPC,但是有一个protobuf-net.Grpc包。
-
确实,使用 protobuf-net.Grpc,在那里敲一些 [ProtoContract]/[ProtoMember(N)] 属性,然后:你完成了。 gRPC 边界可以通过接口来描述,工作完成
标签: c# .net-core protocol-buffers grpc