1.新建控制台项目,通过Nuget 加载Protobuf-net
using protobuf_序列化学习.model;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
using ProtoBuf;
namespace protobuf_序列化学习
{
class Program
{
static void Main(string[] args)
{
Person person = new Person() { id = 1, age = 10, name = "Talent", hashDic = new Dictionary<string, int>(), address = new Address { Line1 = "中国", Line2 = "日本" } };
using (MemoryStream ms = new MemoryStream())
{
Serializer.Serialize(ms, person);
ms.Position = 0;
Person res = Serializer.Deserialize<Person>(ms);
Console.WriteLine(res.ToString());
Console.ReadKey();
}
DataHolder dataholder = new DataHolder();
dataholder.intHolder.Add("int", 100);
dataholder.stringHolder.Add("string", "haha");
using (MemoryStream ms2 = new MemoryStream())
{
Serializer.Serialize<DataHolder>(ms2, dataholder);
ms2.Position = 0;
DataHolder dataRes = Serializer.Deserialize<DataHolder>(ms2);
int intres = (int)dataRes.intHolder["int"];
string stringres = (string)dataRes.stringHolder["string"];
Console.WriteLine("Int :" + intres + ", stringres :" + stringres);
Console.ReadKey();
}
//可以用一下方法 生成 .proto
Console.WriteLine( ProtoBuf.Meta.RuntimeTypeModel.Default.GetSchema(typeof(Person)));
Console.ReadKey();
}
}
}
[ProtoContract]
public class Address
{
[ProtoMember(1)]
public string Line1 { get; set; }
[ProtoMember(2)]
public string Line2 { get; set; }
public override string ToString()
{
return " Line1:" + Line1 + ", Line2:" + Line2;
}
}
[ProtoContract]
public class Person
{
[ProtoMember(1)]
public int id;
[ProtoMember(2)]
public int age;
[ProtoMember(3)]
public string name;
[ProtoMember(4)]
public Address address;
public override string ToString()
{
return "Person ..id:" + this.id + ", age:" + this.age + ", name:" + this.name + ", address:" + address.ToString();
}
}