SinglePrimitiveAccessor.cs 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. using System;
  2. using System.Reflection;
  3. using Google.ProtocolBuffers.Descriptors;
  4. namespace Google.ProtocolBuffers.FieldAccess {
  5. /// <summary>
  6. /// Access for a non-repeated field of a "primitive" type (i.e. not another message or an enum).
  7. /// </summary>
  8. internal class SinglePrimitiveAccessor : IFieldAccessor {
  9. private readonly PropertyInfo messageProperty;
  10. private readonly PropertyInfo builderProperty;
  11. private readonly PropertyInfo hasProperty;
  12. private readonly MethodInfo clearMethod;
  13. /// <summary>
  14. /// The CLR type of the field (int, the enum type, ByteString, the message etc).
  15. /// As declared by the property.
  16. /// </summary>
  17. protected Type ClrType {
  18. get { return messageProperty.PropertyType; }
  19. }
  20. internal SinglePrimitiveAccessor(string name, Type messageType, Type builderType) {
  21. messageProperty = messageType.GetProperty(name);
  22. builderProperty = builderType.GetProperty(name);
  23. hasProperty = messageType.GetProperty("Has" + name);
  24. clearMethod = builderType.GetMethod("Clear" + name);
  25. if (messageProperty == null || builderProperty == null || hasProperty == null || clearMethod == null) {
  26. throw new ArgumentException("Not all required properties/methods available");
  27. }
  28. }
  29. public bool Has(IMessage message) {
  30. return (bool) hasProperty.GetValue(message, null);
  31. }
  32. public void Clear(IBuilder builder) {
  33. clearMethod.Invoke(builder, null);
  34. }
  35. /// <summary>
  36. /// Only valid for message types - this implementation throws InvalidOperationException.
  37. /// </summary>
  38. public virtual IBuilder CreateBuilder() {
  39. throw new InvalidOperationException();
  40. }
  41. public virtual object GetValue(IMessage message) {
  42. return messageProperty.GetValue(message, null);
  43. }
  44. public virtual void SetValue(IBuilder builder, object value) {
  45. builderProperty.SetValue(builder, value, null);
  46. }
  47. #region Methods only related to repeated values
  48. public int GetRepeatedCount(IMessage message) {
  49. throw new InvalidOperationException();
  50. }
  51. public object GetRepeatedValue(IMessage message, int index) {
  52. throw new InvalidOperationException();
  53. }
  54. public void SetRepeated(IBuilder builder, int index, object value) {
  55. throw new InvalidOperationException();
  56. }
  57. public void AddRepeated(IBuilder builder, object value) {
  58. throw new InvalidOperationException();
  59. }
  60. public object GetRepeatedWrapper(IBuilder builder) {
  61. throw new InvalidOperationException();
  62. }
  63. #endregion
  64. }
  65. }