簡體   English   中英

Protobuf-net使用接口和抽象基類創建TypeModel

[英]Protobuf-net creating typemodel with interface and abstract baseclass

我正在嘗試使用出色的Protobuf-NET序列化模型。 我不能使用屬性(在編譯時對象是未知的),所以我構造了TypeModel。 我的對象模型包含一個TestDataObject類,該類具有ITestDataExtension屬性。 抽象基類TestDataExtensionBase實現此接口,而類TestDataExtension (代碼中的myDataObjectExtA)從該基類繼承。

我的TypeModel的構造如下:

        System.IO.MemoryStream tmpMemoryStream = new System.IO.MemoryStream();
        RuntimeTypeModel model = TypeModel.Create();
        MetaType basetype = model.Add(typeof(TestDataObject), true);
        MetaType interfaceType = model.Add(typeof(ITestDataExtension), true);
        //MetaType extBaseType = interfaceType.AddSubType(100, typeof(TestDataExtensionBase));
        MetaType extType = interfaceType.AddSubType(200, myDataObjectExtA.GetType());
        model.Add(typeof(TestDataExtensionBase), true);
        model.Add(myDataObjectA.Ext.GetType(), true);
        model.CompileInPlace();
        model.Serialize(tmpMemoryStream, myDataObjectA);
        byte[] tmpDat = tmpMemoryStream.ToArray();

如果運行以下命令,則不會對基類的屬性進行序列化,因此我需要對它們進行序列化。
我認為我應該為TestDataExtensionBase添加一個子類型,如下所示:

        MetaType extBaseType = interfaceType.AddSubType(100, typeof(TestDataExtensionBase));
        MetaType extType = extBaseType.AddSubType(200, myDataObjectExtA.GetType());

但是,這導致了:意外的子類型:TestDataExtension。 有人知道我在做什么錯嗎? 任何幫助,將不勝感激。

2個問題:

  • 目前僅為成員提供接口支持,而不為根對象提供接口支持(由於存在多個接口繼承問題); 解決此問題的最簡單方法是將包裝對象與接口成員一起使用
  • 有必要在模型中定義子類型

認為以下是您的描述...?

using System;
using ProtoBuf.Meta;

interface ITest
{
    int X { get; set; }
}
abstract class TestBase : ITest
{
    public int X { get; set; } // from interface
    public int Y { get; set; }
}
class Test : TestBase
{
    public int Z { get; set; }
    public override string ToString()
    {
        return string.Format("{0}, {1}, {2}", X, Y, Z);
    }
}
class Wrapper
{
    public ITest Value { get; set; }
}
public class Program
{
    static void Main()
    {
        var model = TypeModel.Create();
        model.Add(typeof (ITest), false).Add("X")
                .AddSubType(10, typeof (TestBase));
        model.Add(typeof (TestBase), false).Add("Y")
                .AddSubType(10, typeof (Test));
        model.Add(typeof (Test), false).Add("Z");
        model.Add(typeof (Wrapper), false).Add("Value");

        Wrapper obj = new Wrapper {Value = new Test()
                {X = 123, Y = 456, Z = 789}};

        var clone = (Wrapper)model.DeepClone(obj);
        Console.WriteLine(clone.Value);
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM