GeneratedRepeatException.cs 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. // Protocol Buffers - Google's data interchange format
  2. // Copyright 2008 Google Inc.
  3. // http://code.google.com/p/protobuf/
  4. //
  5. // Licensed under the Apache License, Version 2.0 (the "License");
  6. // you may not use this file except in compliance with the License.
  7. // You may obtain a copy of the License at
  8. //
  9. // http://www.apache.org/licenses/LICENSE-2.0
  10. //
  11. // Unless required by applicable law or agreed to in writing, software
  12. // distributed under the License is distributed on an "AS IS" BASIS,
  13. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14. // See the License for the specific language governing permissions and
  15. // limitations under the License.
  16. using System;
  17. using System.Collections.Generic;
  18. using Google.ProtocolBuffers.Descriptors;
  19. using System.Collections;
  20. namespace Google.ProtocolBuffers {
  21. /// <summary>
  22. /// Class used to represent repeat extensions in generated classes.
  23. /// </summary>
  24. public sealed class GeneratedRepeatExtension<TExtensionElement> : GeneratedExtensionBase<IList<TExtensionElement>> {
  25. private GeneratedRepeatExtension(FieldDescriptor field) : base(field, typeof(TExtensionElement)) {
  26. }
  27. public static GeneratedExtensionBase<IList<TExtensionElement>> CreateInstance(FieldDescriptor descriptor) {
  28. if (!descriptor.IsRepeated) {
  29. throw new ArgumentException("Must call GeneratedRepeatExtension.CreateInstance() for repeated types.");
  30. }
  31. return new GeneratedRepeatExtension<TExtensionElement>(descriptor);
  32. }
  33. /// <summary>
  34. /// Converts the list to the right type.
  35. /// TODO(jonskeet): Check where this is used, and whether we need to convert
  36. /// for primitive types.
  37. /// </summary>
  38. /// <param name="value"></param>
  39. /// <returns></returns>
  40. public override object FromReflectionType(object value) {
  41. if (Descriptor.MappedType == MappedType.Message ||
  42. Descriptor.MappedType == MappedType.Enum) {
  43. // Must convert the whole list.
  44. List<TExtensionElement> result = new List<TExtensionElement>();
  45. foreach (object element in (IEnumerable) value) {
  46. result.Add((TExtensionElement) SingularFromReflectionType(element));
  47. }
  48. return result;
  49. } else {
  50. return value;
  51. }
  52. }
  53. }
  54. }