SingleEnumAccessor.cs 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  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 Google.ProtocolBuffers.Descriptors;
  18. namespace Google.ProtocolBuffers.FieldAccess {
  19. /// <summary>
  20. /// Accessor for fields representing a non-repeated enum value.
  21. /// </summary>
  22. internal sealed class SingleEnumAccessor<TMessage, TBuilder> : SinglePrimitiveAccessor<TMessage, TBuilder>
  23. where TMessage : IMessage<TMessage, TBuilder>
  24. where TBuilder : IBuilder<TMessage, TBuilder> {
  25. private readonly EnumDescriptor enumDescriptor;
  26. internal SingleEnumAccessor(FieldDescriptor field, string name) : base(name) {
  27. enumDescriptor = field.EnumType;
  28. }
  29. /// <summary>
  30. /// Returns an EnumValueDescriptor representing the value in the builder.
  31. /// Note that if an enum has multiple values for the same number, the descriptor
  32. /// for the first value with that number will be returned.
  33. /// </summary>
  34. public override object GetValue(TMessage message) {
  35. // Note: This relies on the fact that the CLR allows unboxing from an enum to
  36. // its underlying value
  37. int rawValue = (int) base.GetValue(message);
  38. return enumDescriptor.FindValueByNumber(rawValue);
  39. }
  40. /// <summary>
  41. /// Sets the value as an enum (via an int) in the builder,
  42. /// from an EnumValueDescriptor parameter.
  43. /// </summary>
  44. public override void SetValue(TBuilder builder, object value) {
  45. EnumValueDescriptor valueDescriptor = (EnumValueDescriptor) value;
  46. base.SetValue(builder, valueDescriptor.Number);
  47. }
  48. }
  49. }