SampleUsage.cs 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344
  1. using System;
  2. using System.IO;
  3. namespace Google.ProtocolBuffers.Examples.AddressBook
  4. {
  5. class SampleUsage
  6. {
  7. static void Main()
  8. {
  9. byte[] bytes;
  10. //Create a builder to start building a message
  11. Person.Builder newContact = Person.CreateBuilder();
  12. //Set the primitive properties
  13. newContact.SetId(1)
  14. .SetName("Foo")
  15. .SetEmail("foo@bar");
  16. //Now add an item to a list (repeating) field
  17. newContact.AddPhone(
  18. //Create the child message inline
  19. Person.Types.PhoneNumber.CreateBuilder().SetNumber("555-1212").Build()
  20. );
  21. //Now build the final message:
  22. Person person = newContact.Build();
  23. //The builder is no longer valid (at least not now, scheduled for 2.4):
  24. newContact = null;
  25. using(MemoryStream stream = new MemoryStream())
  26. {
  27. //Save the person to a stream
  28. person.WriteTo(stream);
  29. bytes = stream.ToArray();
  30. }
  31. //Create another builder, merge the byte[], and build the message:
  32. Person copy = Person.CreateBuilder().MergeFrom(bytes).Build();
  33. //A more streamlined approach might look like this:
  34. bytes = AddressBook.CreateBuilder().AddPerson(copy).Build().ToByteArray();
  35. //And read the address book back again
  36. AddressBook restored = AddressBook.CreateBuilder().MergeFrom(bytes).Build();
  37. //The message performs a deep-comparison on equality:
  38. if(restored.PersonCount != 1 || !person.Equals(restored.PersonList[0]))
  39. throw new ApplicationException("There is a bad person in here!");
  40. }
  41. }
  42. }