How can I use AddSubType on a type that is a collection?
RuntimeTypeModel.Default[typeof(IMyClass2)].AddSubType(1, typeof(MyClass)) threw "Repeated data (a list, collection, etc) has inbuilt behaviour and cannot be subclassed" exception. Following is the code snippet
public partial class TestClass
{
public TestClass()
{
}
private void Serialize(object sender, EventArgs e)
{
Stream stream = new FileStream(resultFilePath,
FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.None);
RuntimeTypeModel.Default[typeof(IMyClass2)].AddSubType(1, typeof(MyClass));
Serializer.Serialize(stream, myDict);
stream.Close();
}
开发者_如何学Python private void DeSerialize(object sender, EventArgs e)
{
Stream stream = new
FileStream(resultFilePath, FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.None);
Dictionary<int, IMyClass2> myNewDict = Serializer.Deserialize<Dictionary<int, IMyClass2>>(stream);
stream.Close();
}
}
[ProtoContract]
[Serializable]
public class MyClass : IMyClass2
{
#region IMyClass2 Members
//members
#endregion
#region IEnumerable Members
public IEnumerator GetEnumerator()
{
throw new NotImplementedException();
}
#endregion
}
public interface IMyClass2 : IMyClass1
{
//members
}
public interface IMyClass1 : IEnumerable
{
//members
}
How should I handle this exception? Please help.
protobuf-net has concluded (quite reasonably) that your base-type there is a collection-type. Collections (in common with most other serializers and data-binding etc) get treated differently to individual items. In "protocol buffers" this is even more pronounced, since the container doesn't even exist in the stream - all that is serialized is the individual elements. To illustrate this in xml terms (clarification: protobuf-net is nothing to do with xml, but this helps visualise), then in xml there are 2 approaches for sub-items:
<foo> <foo>
<items> <bar/>
<bar/> <bar/>
<bar/> <bar/>
<bar/> </foo>
</items>
</foo>
of those, protobuf-net would be more like the example on the right - there is no representation at all of the container (items
).
Because of this (which is related to the Google specification, not protobuf-net's implementation), it cannot store anything particular to the collection, so it does not have anywhere to note any particulars like inheritance (which also doesn't exist in the Google specification, but I can work around it for individual items).
In short, I would suggest "don't do that". Perhaps if I understood the scenario a bit more completely I could give a more useful answer.
Note (as hinted above) that it can handle inheritance of individual items, so a List<SomeBaseType>
can contain DerivedType1
, DerivedType2
and YetAnotherDerivedType
instances.
精彩评论