将Protobuf-net代理与List <t>一起使用

时间:2019-03-08 16:53:02

标签: protobuf-net

这里星期五下午真正出现了脑衰竭! :-(

现实世界中的Foo和Bar是3rd party库中的类型,不支持序列化。

(对这个问题不重要,但为清楚起见,我不需要转换回来,我将针对需要实现的重播场景对代理类型进行反序列化。)

class Program
{
    static void Main(string[] args)
    {
        RuntimeTypeModel.Create();
        var model = RuntimeTypeModel.Default;

        model.Add(typeof(Foo), false).SetSurrogate(typeof(FooSurrogate));
        model.Add(typeof(Bar), false).SetSurrogate(typeof(BarSurrogate));

        var st = new List<Bar> { new Bar { String1 = "Text1" }, new Bar { String1 = "Text2" } };

        var ct = new Foo { Index = 99, Bars = st };

        using (var outputStream = File.Create("foo.bin"))
        {
            Serializer.Serialize(outputStream, ct);
        }
    }
}


public class Foo
{
    public int Index { get; set; }


    public List<Bar> Bars { get; set; }
}



public class Bar
{
    public string String1 { get; set; }
}

[ProtoContract]
public class FooSurrogate
{
    public static implicit operator FooSurrogate(Foo value)
    {
        var fs = new FooSurrogate
        {
            Index = value.Index
        };

        return fs;
    }

    public static implicit operator Foo(FooSurrogate value)
    {
        throw new NotImplementedException();    // I'm never going to need this conversion
    }

    [ProtoMember(1)] public int Index { get; set; }

    [ProtoMember(2)] public List<BarSurrogate> Bars { get; set; }
}


[ProtoContract]
public class BarSurrogate
{
    public static implicit operator BarSurrogate(Bar value)
    {
        return new BarSurrogate
        {
            String1 = value.String1
        };
    }

    public static implicit operator Bar(BarSurrogate value)
    {
        throw new NotImplementedException();    // I'm never going to need this conversion
    }

    [ProtoMember(1)]
    public string String1 { get; set; }

}

如何处理\处理列表栏?

编辑:我可以通过如下修改FooSurrogate类来获得满意的结果;这是我应该怎么做,还是有更好和/或更容易的选择?

    [ProtoContract]
public class FooSurrogate
{
    public static implicit operator FooSurrogate(Foo value)
    {
        if (value == null) return null;

        var fs = new FooSurrogate
        {
            Index = value.Index
        };

        if (value.Bars != null)
        {
            fs.Bars = new List<BarSurrogate>();
            foreach (var bar in value.Bars)
            {
                fs.Bars.Add(bar);
            }
        }

        return fs;
    }

    public static implicit operator Foo(FooSurrogate value)
    {
        throw new NotImplementedException();    // I'm never going to need this conversion
    }

    [ProtoMember(1)]
    public int Index { get; set; }

    [ProtoMember(2)]
    public IList<BarSurrogate> Bars { get; set; }
}

0 个答案:

没有答案