使用protobuf-net 进行协议的序列化

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();
        }
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值