我在反序列化时遇到了这个错误:
无效的线型;这通常意味着您在不截断或设置长度的情况下覆盖了文件;见Using Protobuf-net, I suddenly got an exception about an unknown wire-type
仅提及文件截断,但我正在创建新文件
Stopwatch sw = new Stopwatch();
List<SomeClass> items = CreateSomeClass();
sw.Start();
using (var file = File.Create(fileName))
{
var model = CreateModel();
model.Serialize(file, items);
file.SetLength(file.Position);
}
sw.Stop();
logger.Debug("Saving/serialization to {0} took {1} m/s", fileName, sw.ElapsedMilliseconds);
sw.Reset();
logger.Debug("Starting deserialzation...");
sw.Start();
using (var returnStream = new FileStream(fileName, FileMode.Open))
{
var model = CreateModel();
var deserialized = model.Deserialize(returnStream, null, typeof(SomeClass));
}
logger.Debug("Retrieving/deserialization of {0} took {1} m/s", fileName, sw.ElapsedMilliseconds);
public static TypeModel CreateModel()
{
RuntimeTypeModel model = TypeModel.Create();
model.Add(typeof(SomeClass), false)
.Add(1, "SomeClassId")
.Add(2, "FEnum")
.Add(3, "AEnum")
.Add(4, "Thing")
.Add(5, "FirstAmount")
.Add(6, "SecondAmount")
.Add(7, "SomeDate");
TypeModel compiled = model.Compile();
return compiled;
}
public enum FirstEnum
{
First = 0,
Second,
Third
}
public enum AnotherEnum
{
AE1 = 0,
AE2,
AE3
}
[Serializable()]
public class SomeClass
{
public int SomeClassId { get; set; }
public FirstEnum FEnum { get; set; }
public AnotherEnum AEnum { get; set; }
string thing;
public string Thing
{
get{return thing;}
set
{
if (string.IsNullOrEmpty(value))
throw new ArgumentNullException("Thing");
thing = value;
}
}
public decimal FirstAmount { get; set; }
public decimal SecondAmount { get; set; }
public decimal ThirdAmount { get { return FirstAmount - SecondAmount; } }
public DateTime? SomeDate { get; set; }
}
我是Protobuf-net的新手,所以有什么明显我做错了/丢失了吗?
答案 0 :(得分:2)
您将其序列化为列表,并将其反序列化为单个项目。这是个问题。使用DeserializeItems,或:而不是
typeof(SomeClass)
通
typeof(List<SomeClass>)
DeserializeItems可能稍快一些(由于各种原因,当使用列表类型作为操作数调用Deserialize时,它必须做额外的工作)。
答案 1 :(得分:1)
鉴于错误似乎表明反序列化读者想要读取其他字节,请尝试运行不带file.SetLength(file.Position)的代码,这不应该是需要的(文件流知道它的长度) )。