SingleEnumAccessor.cs 2.1 KB

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