本文介绍了protobuf网的[ProtoInclude(1," MyClass的")没有工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用C#.net 4.0应用程序protobuf网测试版V2 R431。在我的应用我有一个词典< INT,IMyClass> ,我需要序列化。类 MyClass的工具 IMyClass 接口。根据protobuf的的单证我写的代码下的:

I am using protobuf-net v2 beta r431 for C# .net 4.0 application. In my application I have a Dictionary<int, IMyClass> which i need to serialize. A class MyClass implements IMyClass interface. As per protobuf's documentations I wrote the code as under:

[ProtoContract]
[ProtoInclude(1, typeof(MyClass))]
public interface IMyClass
{
    int GetId();
    string GetName();
}

[ProtoContract]
[Serializable]
public class MyClass : IMyClass
{
    [ProtoMember(1)]
    private int m_id = 0;

    [ProtoMember(2)]
    private string m_name = string.Empty;

    public MyClass(int id, string name)
    {
        m_id = id;
        m_name = name;
    }

    public MyClass()
    {
    }

    #region IMyClass Members

    public int GetId()
    {
        return m_id;
    }

    public string GetName()
    {
        return m_name;
    }

    #endregion
}



不过,按我的应用程序的设计,接口在较高的级别定义(在不同的项目比类),它是无法确定实现在编译时这个接口的类/班。因此,它提供了编译时错误[ProtoInclude(1的typeof(MyClass的))。我试图用[ProtoInclude(INT标签,串KownTypeName)如下:

However, as per my application's design, the interface is defined at a higher level (in a different project than the classes) and it is not possible to determine the class/classes that implements this interface at compile time. Hence, it gives compile time error for [ProtoInclude(1, typeof(MyClass))]. I tried to use [ProtoInclude(int tag, string KownTypeName)] as following:

[ProtoContract]
[ProtoInclude(1, "MyClass")]
public interface IMyClass
{
    int GetId();
    string GetName();
}



但是,这引发了对象引用未设置到对象的实例在行例外

But, this threw an "Object reference not set to instance of an object" exception at line

Serializer.Serialize(stream, myDict);



在这里解释myDict =新词典(INT,IMyClass)();
请让我知道如何使用ProtoInclude在这种情况下,以序列里面字典/列表接口类型。

where Dictionary myDict = new Dictionary(int, IMyClass)();Please let me know how to use ProtoInclude in this case so as to serialize interface type inside dictionary / list.

推荐答案

奥斯汀是正确的(我相信):使用程序集限定名(做为一个字符串)应该解决这个

Austin is correct (I believe): using an assembly-qualified name (as a string) should resolve this.

在V2,一个附加选项存在:您可以执行

In v2, an additional option exists: you can perform the mapping at runtime instead of via attributes:

RuntimeTypeModel.Default[typeof(PulicInterface)]
    .AddSubType(1, typeof(Implementation));

这可能是通过静态代码,如果你的应用程序一线知道这两种类型的,或者可能通过一些自定义的配置/反射过程中完成的。

This could be be through static code if your "app" tier knows about both types, or could be done via some custom configuration / reflection process.

这篇关于protobuf网的[ProtoInclude(1,&QUOT; MyClass的&QUOT;)没有工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-16 01:21