Skip to content

Instantly share code, notes, and snippets.

@fhtino
Last active April 7, 2024 07:43
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save fhtino/4b0ef799e1f141ae669670ef9cf11a1a to your computer and use it in GitHub Desktop.
Save fhtino/4b0ef799e1f141ae669670ef9cf11a1a to your computer and use it in GitHub Desktop.
ProtoBuf-net automap
using (var protoFile = File.Create("data.bin"))
{
ProtoBufUtils.GetModel<Customer>().Serialize(protoFile, allCustomers);
}
using (var protoFile = File.OpenRead("data.bin"))
{
_customers = ProtoBufUtils.GetModel<Customer>().Deserialize<List<Customer>>(protoFile);
}
internal class ProtoBufUtils
{
public static RuntimeTypeModel GetModel<T>()
{
// note GetProperties() does not guarantee order. So, added an explicit ordering.
var propertyNames = typeof(T).GetProperties().Select(x => x.Name).OrderBy(x => x).ToArray();
var pbModel = RuntimeTypeModel.Create();
pbModel.Add(typeof(T), false).Add(propertyNames);
return pbModel;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment