Last active
April 7, 2024 07:43
-
-
Save fhtino/4b0ef799e1f141ae669670ef9cf11a1a to your computer and use it in GitHub Desktop.
ProtoBuf-net automap
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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