【问题标题】:Protobuf attributes with a hierarchy of generic classes具有通用类层次结构的 Protobuf 属性
【发布时间】:2009-08-18 21:59:22
【问题描述】:

我有一个看起来像这样的类层次结构。这些类包含许多我已排除的其他细节。这是对这些类的序列化方面的简化。

[ProtoInclude(1, typeof(Query<bool>))]
[ProtoInclude(2, typeof(Query<string>))]
[ProtoInclude(3, typeof(Query<int>))]
[ProtoInclude(4, typeof(Query<decimal>))]
[ProtoInclude(5, typeof(Query<DataSet>))]
abstract class Query
{
    public string Result { get; set; }
}
[ProtoInclude(1, typeof(SpecialQuery)]
abstract class Query<T> : Query
{
    public new T Result { get; set; }
}
abstract class SpecialQuery : Query<DataSet>
{
    public new string Result { get; set; }
}

我还有大约 150 个自动生成的泛型查询后代,具有多种泛型类型。例如:

[ProtoContract]
class W : Query<bool>
{
}
[ProtoContract]
class X : Query<string>
{
}
[ProtoContract]
class Y : Query<int>
{
}
[ProtoContract]
class Z : SpecialQuery
{
}

我还为所有这些类型自动生成了 [ProtoInclude]。例如:

[ProtoInclude(1, typeof(W)]
[ProtoInclude(2, typeof(X)]
[ProtoInclude(3, typeof(Y)]
[ProtoInclude(4, typeof(Z)]

问题是,我如何部署这 150 个 ProtoInclude?我尝试了各种看起来合乎逻辑的组合,但我得到了各种异常,具体取决于哪些属性出现在哪里。上例中实际需要序列化的类型有 W、X、Y、Z,只有 150 种左右。

protobuf-net 甚至可以处理这样的事情,还是我应该尝试其他类型的序列化?

【问题讨论】:

  • 添加第二个答案以解决更新的问题
  • (但保留原件以防将来向其他读者添加上下文)

标签: c# generics inheritance protobuf-net


【解决方案1】:

好的;随着更新的问题,我了解更多。我希望对象模型中间的泛型确实会让生活......“有趣”。它不能“开箱即用”;我查看了是否可以进行一些简单的调整来支持它,但它很快就开始变得丑陋。如果可能的话,我希望简单地删除中间对泛型的需求会更好——也许保留一个泛型 interface (而不是泛型类)。下面是一些可以工作的代码;这如何映射到您的代码...我不能说 100%。请注意,您不必使用 TypeDescriptor 东西(等) - 似乎因为您使用的是代码生成,这可能会使一些事情变得更容易......

(我没有检查 DataSet 的东西 - 只是类的东西)

using System;
using System.ComponentModel;
using System.Data;
using System.IO;
using NUnit.Framework;
using ProtoBuf;

[TestFixture]
public class ComplexGenericTest
{
    [Test]
    public void TestX()
    {
        Query query = new X { Result = "abc" };
        Assert.AreEqual(typeof(string), query.GetQueryType());
        Query clone = Serializer.DeepClone<Query>(query);
        Assert.IsNotNull(clone);
        Assert.AreNotSame(clone, query);
        Assert.IsInstanceOfType(query.GetType(), clone);
        Assert.AreEqual(((X)query).Result, ((X)clone).Result);
    }
    [Test]
    public void TestY()
    {
        Query query = new Y { Result = 1234};
        Assert.AreEqual(typeof(int), query.GetQueryType());
        Query clone = Serializer.DeepClone<Query>(query);
        Assert.IsNotNull(clone);
        Assert.AreNotSame(clone, query);
        Assert.IsInstanceOfType(query.GetType(), clone);
        Assert.AreEqual(((Y)query).Result, ((Y)clone).Result);
    }

}
public static class QueryExt {
    public static Type GetQueryType(this IQuery query)
    {
        if (query == null) throw new ArgumentNullException("query");
        foreach (Type type in query.GetType().GetInterfaces())
        {
            if (type.IsGenericType
                && type.GetGenericTypeDefinition() == typeof(IQuery<>))
            {
                return type.GetGenericArguments()[0];
            }
        }
        throw new ArgumentException("No typed query implemented", "query");
    }
}
public interface IQuery
{
    string Result { get; set; }
}
public interface IQuery<T> : IQuery
{
    new T Result { get; set; }
}

[ProtoInclude(21, typeof(W))]
[ProtoInclude(22, typeof(X))]
[ProtoInclude(23, typeof(Y))]
[ProtoInclude(25, typeof(SpecialQuery))]
[ProtoContract]
abstract class Query : IQuery
{
    public string Result
    {
        get { return ResultString; }
        set { ResultString = value; }
    }
    protected abstract string ResultString { get; set; }

    // these are to allow simple ResultString implementations
    // without the codegen having to worry about int.Parse etc
    protected static string FormatQueryString<T>(T value)
    {
        return TypeDescriptor.GetConverter(typeof(T))
            .ConvertToInvariantString(value);
    }
    protected static T ParseQueryString<T>(string value)
    {
        return (T) TypeDescriptor.GetConverter(typeof(T))
            .ConvertFromInvariantString(value);
    }
}
[ProtoContract]
[ProtoInclude(21, typeof(Z))]
abstract class SpecialQuery : Query, IQuery<DataSet>
{

    public new DataSet Result { get; set; }

    [ProtoMember(1)]
    protected override string ResultString
    {
        get {
            if (Result == null) return null;
            using (StringWriter sw = new StringWriter())
            {
                Result.WriteXml(sw, XmlWriteMode.WriteSchema);
                return sw.ToString();
            }
        }
        set {
            if (value == null) { Result = null; return; }
            using (StringReader sr = new StringReader(value))
            {
                DataSet ds = new DataSet();
                ds.ReadXml(sr, XmlReadMode.ReadSchema);
            }
        }
    }
}

[ProtoContract]
class W : Query, IQuery<bool>
{
    [ProtoMember(1)]
    public new bool Result { get; set; }

    protected override string ResultString
    {
        get {return FormatQueryString(Result); }
        set { Result = ParseQueryString<bool>(value); }
    }
}
[ProtoContract]
class X : Query, IQuery<string>
{
    [ProtoMember(1)]
    public new string Result { get; set; }

    protected override string ResultString
    {
        get { return Result ; }
        set { Result = value; }
    }
}
[ProtoContract]
class Y : Query, IQuery<int>
{
    [ProtoMember(1)]
    public new int Result { get; set; }

    protected override string ResultString
    {
        get { return FormatQueryString(Result); }
        set { Result = ParseQueryString<int>(value); }
    }
}
[ProtoContract]
class Z : SpecialQuery
{
}

【讨论】:

  • 鉴于各个查询是自动生成的,当然可以将 Query 变成一个接口。但是,我忽略了 Query 实现其他通用接口和抽象函数,这意味着必须在每个自动生成的 Query 后代中包含一个实现。很有可能,但不是很理想。对于 protobuf,我能想到的最简单的“快速修复”是允许 ProtoInclude 查看整个继承树,但这会破坏现有代码。
  • 所以考虑到我在使用不同的序列化程序时遇到的问题,我决定在这种情况下只写我自己的。由于被序列化的东西是自动生成的,我放弃了反射,只是自动生成代码来调用自定义序列化/反序列化例程。这不是一个通用的解决方案,但更适合我的独特情况。
【解决方案2】:

我不能 100% 确定我了解您要建模的场景;但是,[ProtoInclude] 看起来只有一层继承。

如果我理解正确,请尝试以下操作;请注意,此时您需要在编译时了解潜在的泛型类型:

using System;
using ProtoBuf;
[ProtoContract]
[ProtoInclude(2, typeof(Response))]
[ProtoInclude(3, typeof(Query))]
class Packet
{
    [ProtoMember(1)]
    int ID;
}
[ProtoContract]
[ProtoInclude(1, typeof(Response<int>))]
[ProtoInclude(2, typeof(Response<decimal>))]
[ProtoInclude(3, typeof(Response<string>))]
class Response : Packet
{
}
[ProtoContract]
class Response<T> : Response
{
    [ProtoMember(2)]
    public T Value;

    public override string ToString()
    {
        return typeof(T).Name + ": " + Value;
    }
}
static class Program
{
    static void Main()
    {
        Packet packet = new Response<int> { Value = 123 };
        Packet clone = Serializer.DeepClone<Packet>(packet);
        Console.WriteLine(clone.ToString()); // should be int/123
    }
}

【讨论】:

  • 很抱歉给您带来了困惑。 Response 有点像红鲱鱼。真正的问题是关于 Query 的约 150 个后代。我修改了我的问题,希望能更清楚地说明我在问什么。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-11-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多