我正在尝试序列化具有不可变基类的不可变消息。但是,我无法说服 protobuf-serializer 将其反序列化为派生类型。简而言之,这个测试给了我一个无效的强制转换异常(从 Base 到 Derived):
[TestFixture]
public class InheritanceTest
{
public class Base
{
public int IntField { get; private set; }
public Base(int intField)
{
IntField = intField;
}
}
public class Derived : Base
{
public string StringField { get; private set; }
public Derived(int intField, string stringField) : base(intField)
{
StringField = stringField;
}
}
[Test]
public void TestInheritance()
{
var serializer = TypeModel.Create();
serializer.Add(typeof (Base), true)
.Add(1, "IntField")
.AddSubType(2, typeof (Derived))
.UseConstructor = false;
serializer.Add(typeof (Derived), true)
.Add(1, "StringField")
.UseConstructor = false;
serializer.CompileInPlace();
using (var stream = new MemoryStream())
{
var message = new Derived(1, "Some text that is not important");
serializer.Serialize(stream, message);
stream.Position = 0;
var retrieved = (Derived) serializer.Deserialize(stream, null, typeof (Derived));
Assert.AreEqual(message.IntField, retrieved.IntField);
Assert.AreEqual(message.StringField, retrieved.StringField);
}
}
}
如果我将 Base 和 Derived 转换为可变类型,此异常就会消失。我做错了什么还是protobuf-net的限制?