Protobuf-net使用示例
本示例使用ProtoBuf的.Net社区版本:https://github.com/mgravell/protobuf-net。创建控制台程序,从NuGet中搜索并安装作者为Marc Gravell的版本。
1、GIthub示例(包含关系)
[ProtoContract]
class Person
{
[ProtoMember(1)]
public int Id { get; set; }
[ProtoMember(2)]
public string Name { get; set; }
[ProtoMember(3)]
public Address Address { get; set; }
}
[ProtoContract]
class Address
{
[ProtoMember(1)]
public string Line1 { get; set; }
[ProtoMember(2)]
public string Line2 { get; set; }
}
2、继承示例
[ProtoContract]
[ProtoInclude(100, typeof(DerivedClass))]
public class BaseClass
{
[ProtoMember(1)]
public int Id { get; set; }
}
[ProtoContract]
public class DerivedClass : BaseClass
{
[ProtoMember(1)]
public string Name { get; set; }
[ProtoMember(2)]
public int Age { get; set; }
}
3、序列化/反序列化
public class ProtoHelper
{
public static byte[] Serialize<T>(T t)
{
var stream = new MemoryStream();
Serializer.Serialize<T>(stream, t);
var bytes = stream.ToArray();
stream.Close();
stream.Dispose();
return bytes;
}
public static T Deserialize<T>(byte[] bytes)
{
var stream = new MemoryStream(bytes);
var t = Serializer.Deserialize<T>(stream);
stream.Close();
stream.Dispose();
return t;
}
}
4、测试类
public class TestProtoBuf
{
private byte[] _bufferPerson;
private byte[] _bufferDerivedClass;
public void Serialize()
{
var person = new Person()
{
Id = 101,
Name = "ZhangSan",
Address = new Address()
{
Line1 = "ZhengZhou",
Line2 = "Kexue Rd."
}
};
Console.WriteLine("Before Person Serialize: {0}, {1}, {2}, {3}",
person.Id, person.Name, person.Address.Line1, person.Address.Line2);
_bufferPerson = ProtoHelper.Serialize(person);
var derivedClass = new DerivedClass()
{
Id = 12,
Name = "test class",
Age = 23
};
Console.WriteLine();
Console.WriteLine("Before DerivedClass Serialize: {0}, {1}, {2}",
derivedClass.Id, derivedClass.Name, derivedClass.Age);
_bufferDerivedClass = ProtoHelper.Serialize(derivedClass);
}
public void Deserialize()
{
if (_bufferPerson != null)
{
var person = ProtoHelper.Deserialize<Person>(_bufferPerson);
Console.WriteLine();
Console.WriteLine("After Person Serialize: {0}, {1}, {2}, {3}",
person.Id, person.Name, person.Address.Line1, person.Address.Line2);
}
if (_bufferDerivedClass != null)
{
var derivedClass = ProtoHelper.Deserialize<DerivedClass>(_bufferDerivedClass);
Console.WriteLine();
Console.WriteLine("After DerivedClass Serialize: {0}, {1}, {2}",
derivedClass.Id, derivedClass.Name, derivedClass.Age);
}
}
}
5、测试代码
var testProtoBuf = new TestProtoBuf();
testProtoBuf.Serialize();
testProtoBuf.Deserialize();