1

我在 .net 中使用协议缓冲区,并使用 protoc 生成 C# 类。例如,让我们从https://developers.google.com/protocol-buffers/docs/proto3获取这个 proto3 文件:

message SearchResponse {
  repeated Result results = 1;
}

message Result {
  string url = 1;
  string title = 2;
  repeated string snippets = 3;
}

让我们尝试初始化生成的 C# 类。

它们看起来像这样

public class SearchResponse
{
    public RepeatedField<Result> Results { get; } = new RepeatedField<Result>();
}

public class Result
{
    public string Url { get; set; }
    public string Title { get; set; }
    public RepeatedField<string> Snippets { get; } = new RepeatedField<string>();
}

现在让我们尝试初始化它。理想情况下,我希望能够做这样的事情:

SearchResponse GetSearchResponse => new SearchResponse
{
    Results = new RepeatedField<SearchResponse>
    {
        new Result
        {
            Url = "..."
            Title = "..."
            Snippets = new RepeatedField<string> {"a", "b", "c"}
        }
    }
};

但是,由于集合没有设置器,因此我必须跨多个表达式对其进行初始化:

SearchResponse GetSearchResponse
{
    get
    {
        var response = new SearchResponse();
        var result = new Result
        {
            Url = "..."
            Title = "..."
        }
        result.Snippets.AddRange(new[]{"a", "b", "c"});
        response.Results.Add(result);
        return response;
    }
}

理想情况下,一个表达式会分布在 5 个表达式和语句的混合体中。

有没有更简洁的方法来初始化我缺少的这些结构?

4

1 回答 1

2

RepeatedField<T>实现列表 API,因此您应该能够只使用集合初始化程序而无需设置新值:

new SearchResponse {
    Results = {
        new Result {
            Url = "...",
            Title = "...",
            Snippets = { "a", "b", "c" }
        }
    }
}
于 2019-01-30T18:00:18.497 回答