简体   繁体   English

使用协议缓冲区模拟泛型

[英]simulate generics with protocol buffer

I have a class that stores and manipulates some entities. 我有一个存储和操作某些实体的类。 Depending on the number of inputs, I may not be able to store entities in memory, so I'm trying to serialize my objects to be written on hard disk using protocol buffers. 根据输入的数量,我可能无法将实体存储在内存中,因此我尝试使用协议缓冲区将我的对象序列化以写入硬盘。 I'm using C# and protobuf-csharp-port . 我正在使用C#和protobuf-csharp-port I'm aware of protobuf-net as an alternative port; 我知道protobuf-net是一个替代端口; so far I have been working with first option but I'm open for changes if it's required based on my needs. 到目前为止,我一直在使用第一个选项,但如果需要根据我的需要我可以进行更改。

The class to be serialized in it's simplified form is as follows: 要以其简化形式序列化的类如下:

class Entity<T> where T: IComparable<T>
{
    int id;
    T metaData;
}

So at compile time I have no clues about metaData . 所以在编译时我没有关于metaData线索。 Googling I noticed that extensions are the right path to follow (as suggested on google's page and this question ); 谷歌搜索我注意到扩展是正确的路径(如谷歌的页面这个问题所示 ); hence I'm defining the Entity.proto file for class Entity as following: 因此我正在为类Entity定义Entity.proto文件,如下所示:

message Entity
{
    required int32 id = 1 [default = 0];
    extensions 2 to max; 
}

and I would like the user to provide his own .proto file for T without the need to access or re-compile Entity.proto . 我希望用户为T提供自己的.proto文件,而无需访问或重新编译Entity.proto In this regard, my questions are: 在这方面,我的问题是:

  1. Do I need to change Entity.proto ? 我需要更改Entity.proto吗?
  2. What should be the T.proto ? 什么应该是T.proto
  3. How can I access T in my C# code ? 如何在C#代码中访问T

With that scheme, any extensions are going to be child values (not subclasses) of the non-generic Entity . 使用该方案,任何扩展都将成为非通用Entity 子值 (而不是子类)。 That doesn't sound like generics, but ultimately storage (serialization) is often quite different to implementation ( Entity<T> etc). 这听起来不像泛型,但最终存储(序列化)通常与实现( Entity<T>等)完全不同。 If you can manuallyap between them: fine. 如果你可以在他们之间手动:好。 But it isn't something the library will provide, AFAIK. 但这不是图书馆提供的东西,AFAIK。

For completeness, in protobuf-net terms: it is perfectly fine with Entity<T> - it essentially considers each ( Entity<Foo> , Entity<Bar> , etc) to be completely separate messages. 为了完整性,在protobuf-net术语中:它与Entity<T>完全没有关系 - 它基本上将每个( Entity<Foo>Entity<Bar>等)视为完全独立的消息。 Protobuf-net isn't hugely motivated by .proto schemas (although a code-gen tool is provided, for completeness) - it mainly uses runtime metadata. Protobuf-net并没有受到.proto模式的巨大推动(尽管提供了代码生成工具,为了完整性) - 它主要使用运行时元数据。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM