2

I have a problem serializing derived classes using protobuf-net. I don't know if it is because it is not supported, or I am doing something wrong.

I have a generic base class (which I can serialize directly) and then i make a specialization of this, but this one I can't serialize. The following is the code for the two classes and a example of usage. Am i doing something wrong?

Edit

Added restriction to the generic types

Base

[ProtoBuf.ProtoContract]
public class Base<TKey, TValue>
    where TKey : Key
    where TValue : Key
{
    [ProtoBuf.ProtoMember(1)]
    public Dictionary<TKey, Dictionary<TKey, TValue>> Data { get; set; }
    [ProtoBuf.ProtoMember(2)]
    public TValue DefaultValue { get; set; }

    public Base()
    {
        this.Data = new Dictionary<TKey, Dictionary<TKey, TValue>>();
    }

    public Base(TValue defaultValue)
        : this()
    {
        this.DefaultValue = defaultValue;
    }

    public TValue this[TKey x, TKey y]
    {
        get
        {
            try { return this.Data[x][y]; }
            catch { return this.DefaultValue; }
        }
        set
        {
            if (!this.Data.ContainsKey(x))
                this.Data.Add(x, new Dictionary<TKey, TValue> { { y, value } });
            else
                this.Data[x][y] = value;
        }
    }
}

Key class

public abstract class Key
{
}

Specialized key

[ProtoBuf.ProtoContract]
public class IntKey : Key
{
    [ProtoBuf.ProtoMember(1)]
    public int Value { get; set; }

    public IntKey() { }

    public override int GetHashCode()
    {
        return this.Value.GetHashCode();
    }

    public override bool Equals(object obj)
    {
        if (ReferenceEquals(obj, null)) return false;
        if (ReferenceEquals(obj, this)) return true;

        var s = obj as IntKey;
        return this.Value.Equals(s.Value);
    }
}

Specialized class

[ProtoBuf.ProtoContract]
public class IntWrapper<TKey> : Base<TKey, IntKey>
    where TKey : Key
{
    public IntWrapper()
        : base() { }

    public IntWrapper(IntKey defaultValue)
        : base(defaultValue) { }
}

An example of usage

var path = @"C:\Temp\data.dat";
var data = new IntWrapper<IntKey>(new IntKey { Value = 0 }); // This will not be serialized
for(var x = 0; x < 10; x++)
{
    for(var y = 0; y < 10; y++)
        data[new IntKey { Value = x }, new IntKey { Value = y }] = new IntKey { Value = x + y };
}

using (var fileStream = new FileStream(path, FileMode.Create))
{
    ProtoBuf.Serializer.Serialize(fileStream, data);
}
aweis
  • 5,350
  • 4
  • 30
  • 46

1 Answers1

2

The model needs to understand in proto terms the relationship between base-type and sub-type, in particular the field used to uniquely identify it. Usually this would be done with attributes on the base type, but this is problematic when using generics, because you can't use typeof(SomeType<TKey>) in an attribute. You can define this at runtime, though:

RuntimeTypeModel.Default.Add(typeof (Base<int,int>), true)
              .AddSubType(3, typeof (IntWrapper<int>));

After that, it works.

Marc Gravell
  • 1,026,079
  • 266
  • 2,566
  • 2,900
  • Okay, what if i limit the scope of the generic type to inherit from a certain abstract class (I added this to the Q). So now the base structure only allows types that are of type `Key` will this make it easier? – aweis Mar 02 '12 at 10:04
  • @aweis would need to see a concrete example; but: most **common** scenarios can be handled with `[ProtoInclude(...)]` – Marc Gravell Mar 02 '12 at 10:25
  • The example is pretty much the code in the question. My biggest problem is that I have no control over what types there are given to the base class, but I can require them to be serializable, so I thought that limiting them to inherit a specific base class would also limiting the scope! – aweis Mar 02 '12 at 10:31
  • @aweis protobuf-net, in common with things like XmlSerializer, likes the structure to be known ahead of time... it isn't designed to serialize completely unpredictable types – Marc Gravell Mar 02 '12 at 10:46
  • Okay, then I will do some redesigning. Thanks. – aweis Mar 02 '12 at 11:31