我整天都尝试过使用protobuf-net软件包,但我还没有成功。详细说明了我尝试运行代码所采取的步骤:
我在程序开头放了以下几行代码:
using ProtoBuf;
类的代码是:
[ProtoContract]
class Person {
public Person(int id, string name, Address address)
{
this.Id = id; this.Name = name; this.Address = address;
}
public override string ToString()
{
return "\nPerson.ID" + this.Id + "\nPerson.NAME = " + this.Name + "\nPerson.ADDRESS >> " + this.Address.ToString();
}
[ProtoMember(1)]
public int Id {get;set;}
[ProtoMember(2)]
public string Name { get; set; }
[ProtoMember(3)]
public Address Address {get;set;}
}
[ProtoContract]
class Address {
public Address(string line1, string line2)
{
this.Line1 = line1; this.Line2 = line2;
}
public override string ToString()
{
return "\n\t\tAddress.Line1 = " + this.Line1 + "\n\t\tAddress.Line2 = " + this.Line2;
}
[ProtoMember(1)]
public string Line1 {get;set;}
[ProtoMember(2)]
public string Line2 {get;set;}
}
测试序列化的执行代码是:
var person = new Person (12345, "Fred", new Address ("Flat 1","The Meadows"));
//
using (var file = File.Create("person.txt"))
{
// I think it works well (in the txt, file is displayed)
Serializer.Serialize<Person>(file, person);
}
//
Person newPerson;
using (var file = File.OpenRead("person.txt"))
{
// EXCEPTION: 'ProtoBuf.ProtoException' in protobuf-net.dll
// INFO: No parameterless constructor found for Person
newPerson = Serializer.Deserialize<Person>(file);
}
MessageBox.Show(newPerson.ToString());
重要:当我第一次执行这些步骤并编译源代码时,屏幕上出现一个带有 TypeModel.cs 文件的对话框但后来突然消失了。我已经回顾了几个论坛,我怀疑 protobuf-net 会自动生成 TypeModel.cs 。 如果这是我的问题,我该如何解决?我怎样才能让protobuf-net回复问我要保存文件的位置 TypeModel.cs ?