FieldDescriptor.cs 2.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Reflection;
  4. using Google.ProtocolBuffers.Collections;
  5. using Google.ProtocolBuffers.DescriptorProtos;
  6. namespace Google.ProtocolBuffers.Descriptors {
  7. public class FieldDescriptor : IndexedDescriptorBase<FieldDescriptorProto, FieldOptions> {
  8. private readonly EnumDescriptor enumType;
  9. private readonly MessageDescriptor parent;
  10. internal FieldDescriptor(FieldDescriptorProto proto,
  11. FileDescriptor file,
  12. MessageDescriptor parent,
  13. int index,
  14. bool isExtension) : base(proto, file, index) {
  15. enumType = null;
  16. this.parent = parent;
  17. }
  18. public bool IsRequired {
  19. get;
  20. set;
  21. }
  22. public MappedType MappedType { get; set; }
  23. public bool IsRepeated { get; set; }
  24. public FieldType FieldType { get; set; }
  25. public int FieldNumber { get; set; }
  26. public bool IsExtension { get; set; }
  27. public MessageDescriptor ContainingType {
  28. get { return parent; }
  29. }
  30. public bool IsOptional { get; set; }
  31. public MessageDescriptor MessageType { get; set; }
  32. public MessageDescriptor ExtensionScope { get; set; }
  33. /// <summary>
  34. /// For enum fields, returns the field's type.
  35. /// </summary>
  36. public EnumDescriptor EnumType {
  37. get {
  38. if (MappedType != MappedType.Enum) {
  39. throw new InvalidOperationException("EnumType is only valid for enum fields.");
  40. }
  41. return enumType;
  42. }
  43. }
  44. /// <summary>
  45. /// The default value for this field. For repeated fields
  46. /// this will always be an empty list. For message fields it will
  47. /// always be null. For singular values, it will depend on the descriptor.
  48. /// </summary>
  49. public object DefaultValue {
  50. get { throw new NotImplementedException(); }
  51. }
  52. /// <summary>
  53. /// Immutable mapping from field type to mapped type. Built using the attributes on
  54. /// FieldType values.
  55. /// </summary>
  56. public static readonly IDictionary<FieldType, MappedType> FieldTypeToWireFormatMap = MapFieldTypes();
  57. private static IDictionary<FieldType, MappedType> MapFieldTypes() {
  58. var map = new Dictionary<FieldType, MappedType>();
  59. foreach (FieldInfo field in typeof(FieldType).GetFields(BindingFlags.Static | BindingFlags.Public)) {
  60. FieldType fieldType = (FieldType)field.GetValue(null);
  61. FieldMappingAttribute mapping = (FieldMappingAttribute)field.GetCustomAttributes(typeof(FieldMappingAttribute), false)[0];
  62. map[fieldType] = mapping.MappedType;
  63. }
  64. return Dictionaries.AsReadOnly(map);
  65. }
  66. }
  67. }