Observe the following code (taken from this question ):
[ProtoContract]
public class B
{
[ProtoMember(1)] public int Y;
}
[ProtoContract]
public class C
{
[ProtoMember(1)] public int Y;
}
class Program
{
static void Main()
{
object b = new B { Y = 2 };
object c = new C { Y = 4 };
using (var ms = new MemoryStream())
{
Serializer.SerializeWithLengthPrefix(ms, b, PrefixStyle.Base128);
Serializer.SerializeWithLengthPrefix(ms, c, PrefixStyle.Base128);
ms.Position = 0;
var b2 = Serializer.DeserializeWithLengthPrefix<B>(ms, PrefixStyle.Base128);
Debug.Assert(((B)b).Y == b2.Y);
var c2 = Serializer.DeserializeWithLengthPrefix<C>(ms, PrefixStyle.Base128);
Debug.Assert(((C)c).Y == c2.Y);
}
}
}
Obviously, the wrong code, because b, and cdeclared to be object, but I is serialized using a common method Serializer.Serialize<T>:
System.ArgumentOutOfRangeException occurred
Message=Specified argument was out of the range of valid values.
Parameter name: index
Source=protobuf-net
ParamName=index
StackTrace:
at ProtoBuf.Meta.BasicList.Node.get_Item(Int32 index)
InnerException:
Everything works fine if I update bhow band chow c. However, I need them to be declared as object, so I assume that I need to serialize them using a non-general method Serializer.NonGeneric.SerializeWithLengthPrefix, the problem is not that I understand the meaning of the additional argument fieldNumberexpected by this method. Can someone explain what it is and how to use it here?
I am using protobuf-net v2.
Thank.
EDIT
:
RuntimeTypeModel.Default.Add(typeof(object), false).AddSubType(1, typeof(B)).AddSubType(2, typeof(C));
, , , (B = 1, C = 2), . ?
EDIT2
, :
public class GenericSerializationHelper<T> : IGenericSerializationHelper
{
void IGenericSerializationHelper.SerializeWithLengthPrefix(Stream stream, object obj, PrefixStyle prefixStyle)
{
Serializer.SerializeWithLengthPrefix(stream, (T)obj, prefixStyle);
}
}
public interface IGenericSerializationHelper
{
void SerializeWithLengthPrefix(Stream stream, object obj, PrefixStyle prefixStyle);
}
...
static void Main()
{
var typeMap = new Dictionary<Type, IGenericSerializationHelper>();
typeMap[typeof(B)] = new GenericSerializationHelper<B>();
typeMap[typeof(C)] = new GenericSerializationHelper<C>();
object b = new B { Y = 2 };
object c = new C { Y = 4 };
using (var ms = new MemoryStream())
{
typeMap[b.GetType()].SerializeWithLengthPrefix(ms, b, PrefixStyle.Base128);
typeMap[c.GetType()].SerializeWithLengthPrefix(ms, c, PrefixStyle.Base128);
ms.Position = 0;
var b2 = Serializer.DeserializeWithLengthPrefix<B>(ms, PrefixStyle.Base128);
Debug.Assert(((B)b).Y == b2.Y);
var c2 = Serializer.DeserializeWithLengthPrefix<C>(ms, PrefixStyle.Base128);
Debug.Assert(((C)c).Y == c2.Y);
}
}
, , - , . , , , .