我有以下基本代码:
[Serializable]
[ProtoContract(ImplicitFields = ImplicitFields.AllFields, SkipConstructor = true, InferTagFromName = true, UseProtoMembersOnly = false,ImplicitFirstTag=10)]
public class BaseCustomDictionary<TKey, TValue>
{
[NonSerialized]
[ProtoIgnore]
private System.Collections.Generic.Dictionary<TKey, System.Collections.ObjectModel.Collection<TValue>> collection;
private System.Collections.Generic.Dictionary<TKey, TValue[]> serializationCollection;
[OnSerializing]
[ProtoBeforeSerialization]
private void OnSerializing(StreamingContext context)
{
serializationCollection = System.Collections.Generic.Dictionary<TKey, TValue[]>();
foreach (KeyValuePair<TKey, System.Collections.ObjectModel.Collection<TValue>> values in collection)
{
TValue[] array = new TValue[values.Value.Count];
values.CopyTo(array, 0);
serializationCollection.Add(values.Key, array);
}
}
[OnDeserialized]
[ProtoAfterDeserialization]
private void OnDeserialized(StreamingContext context)
{
collection = new System.Collections.Generic.Dictionary<TKey, System.Collections.ObjectModel.Collection<TValue>>();
foreach (KeyValuePair<TKey, TValue[]> value in serializationCollection)
{
foreach (TValue v in value.Value)
{
Add(value.Key, v);
}
}
serializationCollection = null;
}
public BaseCustomDictionary()
{
collection = System.Collections.Generic.new Dictionary<TKey, System.Collections.ObjectModel.Collection<TValue>>();
MetaType metaType = RuntimeTypeModel.Default[typeof(BaseCustomDictionary<TKey, TValue>)];
metaType.AddSubType(1, typeof(DerivedCustomDictionary<TKey, TValue>));
}
public void Add(TKey key, TValue value)
{
if (!collection.ContainsKey(key))
{
collection.Add(key, CreateCollection());
}
collection[key].Add(value)
}
public virtual System.Collections.ObjectModel.Collection<TValue> CreateCollection()
{
return new System.Collections.ObjectModel.Collection<TValue>();
}
}
[Serializable]
[ProtoContract(ImplicitFields = ImplicitFields.AllFields, SkipConstructor = true, InferTagFromName = true, UseProtoMembersOnly = false, ImplicitFirstTag=10)]
public class DerivedCustomDictionary<TKey, TValue>
{
public override System.Collections.ObjectModel.Collection<TValue> CreateCollection()
{
return new System.Collections.ObjectModel.ObservableCollection<TValue>();
}
}
[ProtoContract(...)]
[ProtoInclude(1, typeof(DerivedClass))]
public abstract class SomeClass
{
private DerivedCustomDictionary<System.Type, SomeClass> children = new DerivedCustomDictionary<System.Type, SomeClass>();
public DerivedCustomDictionary<System.Type, SomeClass> Children
{
get
{
return children;
}
}
}
public class DerivedClass : SomeClass
{
public string Text
{
get;
set;
}
}
DerivedClass root = new DerivedClass();
//ADD CHILDREN THAT HAVE CHILDREN ETC.
using(FileStream stream = new FileStream("Path", FileMode.Create, FileAccess.Write, FileShare.Read))
{
Serializer.Serialize(stream, root)
}
当我打电话时,Serializer.Serialize(stream, root)
我得到一个错误,它试图将“孩子”的类型投射到BaseClass
不会令人震惊地失败的类型。