微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

Protobuf - 替换通用集合

如何解决Protobuf - 替换通用集合

我在 .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 中插入大量样板的情况下管理这种响应?有什么建议吗?

谢谢!

解决方法

enter image description here


你可以像这样尝试在你的 shell protobuf 中使用 Any 关键字

message MyEntityPagedResult
{
  int32 total_rows = 1;
  any page_data = 2;
}

和你的 C# 客户端和服务器端你可以改变这个任何类型

// Read Person message from detail.
if (status.page_data.Is(__YourClassType__))
{
    var person = status.page_data.Unpack<__YourClassType__>();
    ...
}

注意:在此解决方案中,YourClassType 必须在 proto 中定义为消息类。这可以在我看来没有任何方法可以在 proto 文件中实现类似类型:/

编辑: 此链接还可以提供有关您的问题的详细信息。 :) 有一个很好的编码 :D

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。