PropertyReference.cs 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. using System;
  2. using System.Linq;
  3. using System.Reflection;
  4. namespace SRF.Helpers
  5. {
  6. public class PropertyReference
  7. {
  8. public PropertyReference(object target, PropertyInfo property)
  9. {
  10. SRDebugUtil.AssertNotNull(target, null, null);
  11. this._target = target;
  12. this._property = property;
  13. }
  14. public string PropertyName
  15. {
  16. get
  17. {
  18. return this._property.Name;
  19. }
  20. }
  21. public Type PropertyType
  22. {
  23. get
  24. {
  25. return this._property.PropertyType;
  26. }
  27. }
  28. public bool CanRead
  29. {
  30. get
  31. {
  32. return this._property.GetGetMethod() != null;
  33. }
  34. }
  35. public bool CanWrite
  36. {
  37. get
  38. {
  39. return this._property.GetSetMethod() != null;
  40. }
  41. }
  42. public object GetValue()
  43. {
  44. if (this._property.CanRead)
  45. {
  46. return SRReflection.GetPropertyValue(this._target, this._property);
  47. }
  48. return null;
  49. }
  50. public void SetValue(object value)
  51. {
  52. if (this._property.CanWrite)
  53. {
  54. SRReflection.SetPropertyValue(this._target, this._property, value);
  55. return;
  56. }
  57. throw new InvalidOperationException("Can not write to property");
  58. }
  59. public T GetAttribute<T>() where T : Attribute
  60. {
  61. object obj = this._property.GetCustomAttributes(typeof(T), true).FirstOrDefault<object>();
  62. return obj as T;
  63. }
  64. private readonly PropertyInfo _property;
  65. private readonly object _target;
  66. }
  67. }