protobuf-net序列化反序列化

下载:https://code.google.com/archive/p/protobuf-net/downloadsprotobuf-net 

解压引入protobuf-net.dll

namespace ProtobufProjectTest
{
    class Program
    {
        static void Main(string[] args)
        {
            Person person = new Person();
            person.Id = 90001;
            person.Name = "胡汉三";
            person.Addr = new Address { Line1 = "北大路", Line2 = "清华街" };

            // ProtoBuf序列化
            using (var file = System.IO.File.Create("Person"))
            {
                ProtoBuf.Serializer.Serialize(file, person);
            }

            // ProtoBuf反序列化
            Person binPerson = null;
            using (var file = System.IO.File.OpenRead("Person"))
            {
                binPerson = ProtoBuf.Serializer.Deserialize<Person>(file);
            }

            Console.WriteLine(binPerson.Id);
            Console.WriteLine(binPerson.Name);
            Console.WriteLine(binPerson.Addr.Line1);
            Console.WriteLine(binPerson.Addr.Line2);
        }
    }
}

[ProtoContract]
public class Address
{
    [ProtoMember(1)]
    public string Line1;
    [ProtoMember(2)]
    public string Line2;
}

[ProtoContract]
public class Person
{
    [ProtoMember(1)]
    public int Id;
    [ProtoMember(2)]
    public string Name;
    [ProtoMember(3)]
    public Address Addr;
}

 

posted @ 2016-04-20 11:44  贴心小冰棍  阅读(1072)  评论(0编辑  收藏  举报