【发布时间】:2016-04-26 14:54:16
【问题描述】:
我正在序列化一个只存储属性的对象。 它有一个父继承,但我确保序列化的属性与数字具有不同的索引。
[ProtoContract]
[ProtoInclude(597, typeof(DesiredProto))]
[ProtoInclude(598, typeof(RandomClass1Proto))]
[ProtoInclude(599, typeof(RandomClass2Proto))]
[ProtoInclude(600, typeof(RandomClass3Proto))]
public class BaseProto
{
protected string mName = "";
protected string mOwner = "";
protected VObjectType mVType; //this is an enumeration!
public BaseProto(){}
[ProtoMember(1)]
public String Name
{
get { return mName; }
set { mName = value;}
}
[ProtoMember(2)]
public String Owner
{
get { return mOwner; }
set { mOwner = value;}
}
[ProtoMember(3)]
public VObjectType VType
{
get { return mVType; }
set { mVType = value;}
}
}
然后是 DesiredProto:
[ProtoContract]
public class DesiredProto : BaseProto
{
protected DestinationType mDestType;
protected string mAddress = "";
public DesiredProto()
{
}
[ProtoMember(1)]
public DestinationType DestType //this is an enumeration
{
get { return mDestType; }
set { mDestType = value;}
}
[ProtoMember(2)]
public String Address
{
get { return mAddress; }
set { mAddress = value;}
}
}
现在真正奇怪的部分是序列化似乎是完全正常的。每当我序列化和反序列化这个“DesiredProto”时,如果我忽略错误,它就会起作用。 最后,这不是这些类的完整代码 sn-p,它们要长得多,但希望错误以某种方式包含在其中。
【问题讨论】:
-
DestinationType是什么? -
供参考的小事,但如果您使用的是最新版本的 C#,您可能希望使用自动实现的属性——它们可以省去很多麻烦;例如:
[ProtoMember(2)] public string Address {get;set;}- 编译器与您所做的基本完全相同(在幕后),但没有出现拼写错误的风险(使用错误的字段等) -
DestinationType 是一个枚举!
-
太好了,我猜对了我的示例代码!
-
感谢您的提示,我不知道这些格式也有同样的作用!我正在使用“过时”的软件解决方案。
标签: c# serialization protobuf-net protocol-buffers