2

是否可以使用 protobuf-net 序列化以下类?我已经翻遍了,我找不到这种情况的任何例子?

  [ProtoContract]
  public class Example
  {
    [ProtoMember(1)]
    public ConcurrentDictionary<int, string> CategoryNames;
    [ProtoMember(2)]
    public ConcurrentDictionary<int, int[]> TaxonomyMap;
    [ProtoMember(3)]
    public ConcurrentDictionary<int, Dictionary<int, int>>[] Tokens;  
  }

我目前得到标准的“不支持嵌套或锯齿状列表和数组”。但是,我不确定如何映射这样的类?

编辑: 根据@Marc 下面的建议,我能够成功地使用 protobuf-net 来序列化上面的类。为了完整起见,我在下面添加了我的解决方案:

创建了以下类,其中包含 ModelPartition 对象的列表:

[ProtoContract]
public class GenomeModel
{
    [ProtoMember(1)]
    public ConcurrentDictionary<int, string> categoryNames = 
        new ConcurrentDictionary<int, string>();
    [ProtoMember(2)]
    public ConcurrentDictionary<int, int[]> taxonomyMap = 
        new ConcurrentDictionary<int, int[]>();
    [ProtoMember(3)]
    public List<ModelPartition> geneTokens = new List<ModelPartition>();
}

ModelPartition 对象用于通过将每个索引位置和单个 ConcurrentDictionary 成员保存在单独的 ModelPartition 对象中来“抽象” ConcurrentDictionary 数组,然后将其放置在 GenomeModel.geneTokens ModelPartition 列表中:

[ProtoContract]
public class ModelPartition
{
    [ProtoMember(1)]
    public int partitionNo;
    [ProtoMember(2)]
    public ConcurrentDictionary<int, Dictionary<int, int>> partitionData;

    public ModelPartition(int PartitionNo
               , ConcurrentDictionary<int, Dictionary<int, int>> PartitionData)
    { 
        partitionNo = PartitionNo;
        partitionData = PartitionData;
    }
}

最后,在序列化期间,使用 ModelPartition 作为包装器对象,使用简短的转换将数据从原始“示例”对象加载到 GenomeModel 对象中:

GenomeModel genomeModel = new GenomeModel();
genomeModel.categoryNames = strand.categoryNames;
genomeModel.taxonomyMap = strand.taxonomyMap;

for (int i = 0; i < strand.minhashSignatureSize; i++)
{
    genomeModel.geneTokens.Add(new ModelPartition(i, strand.geneTokens[i]));
}

using (var file = File.Create(commandAgrs[0]))
{
    Serializer.Serialize<GenomeModel>(file, genomeModel);
}

谢谢马克!

4

1 回答 1

1

ConcurrentDictionary<TKey,TValue>工作正常。问题是ConcurrentDictionary<TKey,TValue>[]-本质上KeyValuePair<TKey, TValue>[][](从库的角度来看)与- 即嵌套数组相同的布局。如果您需要,请考虑拥有一个数组(或列表),每个数组都有一个字典,而不是字典数组。

于 2014-04-28T06:53:34.840 回答