【发布时间】:2011-09-07 11:40:07
【问题描述】:
以下场景似乎导致 Protobuf.net 中反序列化异常。我做错了什么吗?有没有办法解决这个问题?
[ProtoContract]
[ProtoInclude(2, typeof(Ant))]
[ProtoInclude(3, typeof(Cat))]
public interface IBeast
{
[ProtoMember(1)]
string Name { get; set; }
}
[ProtoContract]
public class Ant : IBeast
{
public string Name { get; set; }
}
[ProtoContract]
public class Cat : IBeast
{
public string Name { get; set; }
}
[ProtoContract]
[ProtoInclude(1, typeof(AntRule1))]
[ProtoInclude(2, typeof(AntRule2))]
[ProtoInclude(3, typeof(CatRule1))]
[ProtoInclude(4, typeof(CatRule2))]
public interface IRule<T> where T : IBeast
{
bool IsHappy(T beast);
}
[ProtoContract]
public class AntRule1 : IRule<Ant>
{
public bool IsHappy(IAnt beast)
{
return true;
}
}
[ProtoContract]
public class AntRule2 : IRule<Ant>
{
public bool IsHappy(IAnt beast)
{
return true;
}
}
[ProtoContract]
public class CatRule1 : IRule<Cat>
{
public bool IsHappy(ICat beast)
{
return true;
}
}
[ProtoContract]
public class CatRule2 : IRule<Cat>
{
public bool IsHappy(ICat beast)
{
return true;
}
}
public class TestSerialization
{
public void Serialize()
{
var antRules = new List<IRule<Ant>>();
antRules.Add(new AntRule1());
antRules.Add(new AntRule2());
var catRules = new List<IRule<Cat>>();
catRules.Add(new CatRule1());
catRules.Add(new CatRule2());
using (var fs = File.Create(@"c:\temp\antRules.bin"))
{
ProtoBuf.Serializer.Serialize(fs, antRules);
fs.Close();
}
using (var fs = File.OpenRead(@"c:\temp\antRules.bin"))
{
List<IRule<Ant>> list;
list = ProtoBuf.Serializer.Deserialize<List<IRule<Ant>>>(fs);
fs.Close();
}
using (var fs = File.Create(@"c:\temp\catRules.bin"))
{
ProtoBuf.Serializer.Serialize(fs, catRules);
fs.Close();
}
using (var fs = File.OpenRead(@"c:\temp\catRules.bin"))
{
List<IRule<Cat>> list;
list = ProtoBuf.Serializer.Deserialize<List<IRule<Cat>>>(fs);
fs.Close();
}
}
}
【问题讨论】:
-
我很高兴看到,但我在编译您的示例时遇到了困难;添加缺少的
ICat/IAnt后仍然有一些构建失败。如果我玩得太多,我不知道我在看同样的问题......你能发布一个编译的例子吗? -
其实,我认为我有repro...看着
-
啊,对不起,我在编辑和剪切和粘贴的过程中一定丢失了一些东西。如果您需要我重新复制代码,请告诉我。
-
抱歉 - IAnt 和 ICat 不应该存在。规则应该是这样的...... public class AntRule1 : IRule
-
我认为我有足够的时间发布答案 - 无论哪种方式都让我知道。
标签: protobuf-net