I have an hierarchy, lets say BaseClass <- DerivedClass I want to serialize a BaseClass[] array with mixed DerivedClass and BaseClass objects
I use V2 Sourcecode Revision r438 (Aug 9, 2011)Pseudocode: myArray = new BaseClass[] {new BaseClass(), new DerivedClass()};
I tried several declarations, but i don't get the desired result:
[ProtoMember(1, AsReference = true, DynamicType = true)]
private BaseClass[] myArray;
-> Wont deserialize all references are not set
[ProtoMember(1, AsReference = true, DynamicType = true)]
private object[] myArray;
-> deserailze, but array type changed from BaseClass[] to object[]
Any suggetions how i can get my original BaseClass[] array back?
[Edit] Unit Tests:
namespace TechnologyEvaluation.Protobuf.ArrayOfBaseClassTest
{
using System;
using NUnit.Framework;
using ProtoBuf;
using ProtoBuf.Meta;
[ProtoContract]
class BaseClassArrayContainerClass
{
[ProtoMember(1, DynamicType = true)]
public Base[] BaseArray { get; set; }
}
[ProtoContract]
class ObjectArrayContainerClass
{
[ProtoMember(1, DynamicType = true)]
public object[] ObjectArray { get; set; }
}
[ProtoContract]
class Base
{
[ProtoMember(1)]
public string BaseClassText { get; set; }
}
[ProtoContract]
class Derived: Base
{
[ProtoMember(1)]
public string DerivedClassText { get; set; }
}
[TestFixture]
class ArrayOfBaseClassTests : AssertionHelper
{
[Test]
public void TestObjectArrayContainerClass()
{
var model = CreateModel();
var container = new ObjectArrayContainerClass();
container.ObjectArray = this.CreateArray();
var cloned = (ObjectArrayContainerClass) model.DeepClone(container);
Expect(cloned.ObjectArray, Is.Not.Null);
foreach (var obj in cloned.开发者_如何转开发ObjectArray )
{
Expect(obj as Base, Is.Not.Null);
}
Expect(cloned.ObjectArray[1] as Derived, Is.Not.Null);
Expect(cloned.ObjectArray.GetType(), Is.EqualTo(typeof(Base[])));
}
[Test]
public void TestBaseClassArrayContainerClass()
{
var model = CreateModel();
var container = new BaseClassArrayContainerClass();
container.BaseArray = this.CreateArray();
var cloned = (BaseClassArrayContainerClass) model.DeepClone(container);
Expect(cloned.BaseArray, Is.Not.Null);
foreach (var obj in cloned.BaseArray)
{
Expect(obj as Base, Is.Not.Null);
}
Expect(cloned.BaseArray[1] as Derived, Is.Not.Null);
Expect(cloned.BaseArray.GetType(), Is.EqualTo(typeof(Base[])));
}
RuntimeTypeModel CreateModel()
{
RuntimeTypeModel model = RuntimeTypeModel.Create();
model.Add(typeof(ObjectArrayContainerClass), true);
model.Add(typeof(BaseClassArrayContainerClass), true);
model.Add(typeof(Base), true);
model[typeof(Base)].AddSubType(100, typeof(Derived));
return model;
}
Base[] CreateArray()
{
return new Base[] { new Base() { BaseClassText = "BaseClassText" }, new Derived() { BaseClassText = "BaseClassText", DerivedClassText = "DerivedClassText" } };
}
}
}
精彩评论