GeneratedRepeatException.cs 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142
  1. using System;
  2. using System.Collections.Generic;
  3. using Google.ProtocolBuffers.Descriptors;
  4. using System.Collections;
  5. namespace Google.ProtocolBuffers {
  6. /// <summary>
  7. /// Class used to represent repeat extensions in generated classes.
  8. /// </summary>
  9. public class GeneratedRepeatExtension<TContainer, TExtensionElement> : GeneratedExtensionBase<TContainer, IList<TExtensionElement>> {
  10. private GeneratedRepeatExtension(FieldDescriptor field) : base(field, typeof(TExtensionElement)) {
  11. }
  12. public static GeneratedExtensionBase<TContainer, IList<TExtensionElement>> CreateInstance(FieldDescriptor descriptor) {
  13. if (!descriptor.IsRepeated) {
  14. throw new ArgumentException("Must call GeneratedRepeatExtension.CreateInstance() for repeated types.");
  15. }
  16. return new GeneratedRepeatExtension<TContainer, TExtensionElement>(descriptor);
  17. }
  18. /// <summary>
  19. /// Converts the list to the right type.
  20. /// TODO(jonskeet): Check where this is used, and whether we need to convert
  21. /// for primitive types.
  22. /// </summary>
  23. /// <param name="value"></param>
  24. /// <returns></returns>
  25. public override object FromReflectionType(object value) {
  26. if (Descriptor.MappedType == MappedType.Message ||
  27. Descriptor.MappedType == MappedType.Enum) {
  28. // Must convert the whole list.
  29. List<TExtensionElement> result = new List<TExtensionElement>();
  30. foreach (object element in (IEnumerable) value) {
  31. ((IList) result).Add(SingularFromReflectionType(element));
  32. }
  33. return result;
  34. } else {
  35. return value;
  36. }
  37. }
  38. }
  39. }