Unity3D简单使用Protobuf-net(一)

Protobuf 是Google的一个开源序列化库,因为使用的数据压缩算法等优化,序列化的数据较Xml更小,速度更快,因为序列化后数据是以紧凑的二进制流形式展现的,所以几乎不可直接查看。

由于Protobuf不支持.Net3.5及以下版本,所以如果要在Unity3D当中使用,则需要用到第三方的Protobuf-net库。

Protobuf-net也是开源的,项目地址如下:https://github.com/mgravell/protobuf-net

本片文章介绍最简单其最简单的用法,其他用法见后面几篇。

  1. 创建一个C#的控制台程序
  2. 点击项目右键打开“管理NuGet程序包”。
  3. 搜索“Protobuf-net”,并安装,如下:

    这里写图片描述

  4. 编辑测试代码如下:

using System.Collections.Generic;
using System.IO;

namespace ProtoTest_1
{
    [ProtoBuf.ProtoContract]
    class MyClass
    {
        [ProtoBuf.ProtoMember(1)]
        public int _nNumber;
        [ProtoBuf.ProtoMember(2)]
        public string _strName;
        [ProtoBuf.ProtoMember(3)]
        public List<string> _lstInfo;
        [ProtoBuf.ProtoMember(4)]
        public Dictionary<int, string> _dictInfo;
    }

    class Program
    {
        static void Main(string[] args)
        {
            //测试用数据
            MyClass my = new MyClass();
            my._nNumber = 0;
            my._strName = "test";
            my._lstInfo = new List<string>();
            my._lstInfo.Add("a");
            my._lstInfo.Add("b");
            my._lstInfo.Add("c");
            my._dictInfo = new Dictionary<int, string>();
            my._dictInfo.Add(1, "a");
            my._dictInfo.Add(2, "b");
            my._dictInfo.Add(3, "c");

            using (FileStream stream = File.OpenWrite("test.dat"))
            {
                //序列化后的数据存入文件
                ProtoBuf.Serializer.Serialize<MyClass>(stream, my);
            }

            MyClass my2 = null;
            using (FileStream stream = File.OpenRead("test.dat"))
            {
                //从文件中读取数据并反序列化
                my2 = ProtoBuf.Serializer.Deserialize<MyClass>(stream);
            }
        }
    }
}

以上程序实现了MyClass类的序列化与反序列化操作,是不是很简单!

需要注意的是序列化类的类名前需要加上“[ProtoBuf.ProtoContract]”,然后每个字段需要按照顺序在前面加上“[ProtoBuf.ProtoMember(Index)]”,这样才能使用。 
后面将继续讲解protobuf-net的使用动态链接库和直接使用源码的这两种方式。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值