Ingen beskrivning
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

PrivateFieldSetter.cs 1.6KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. using System;
  2. using System.Reflection;
  3. namespace UnityEngine.UI.Tests
  4. {
  5. class PrivateFieldSetter<T> : IDisposable
  6. {
  7. private object m_Obj;
  8. private FieldInfo m_FieldInfo;
  9. private object m_OldValue;
  10. public PrivateFieldSetter(object obj, string field, object value)
  11. {
  12. m_Obj = obj;
  13. m_FieldInfo = typeof(T).GetField(field, BindingFlags.NonPublic | BindingFlags.Instance);
  14. m_OldValue = m_FieldInfo.GetValue(obj);
  15. m_FieldInfo.SetValue(obj, value);
  16. }
  17. public void Dispose()
  18. {
  19. m_FieldInfo.SetValue(m_Obj, m_OldValue);
  20. }
  21. }
  22. static class PrivateStaticField
  23. {
  24. public static T GetValue<T>(Type staticType, string fieldName)
  25. {
  26. var type = staticType;
  27. FieldInfo field = null;
  28. while (field == null && type != null)
  29. {
  30. field = type.GetField(fieldName, BindingFlags.Static | BindingFlags.NonPublic);
  31. type = type.BaseType;
  32. }
  33. return (T)field.GetValue(null);
  34. }
  35. }
  36. static class PrivateField
  37. {
  38. public static T GetValue<T>(this object o, string fieldName)
  39. {
  40. var type = o.GetType();
  41. FieldInfo field = null;
  42. while (field == null && type != null)
  43. {
  44. field = type.GetField(fieldName, BindingFlags.Instance | BindingFlags.NonPublic);
  45. type = type.BaseType;
  46. }
  47. return field != null ? (T)field.GetValue(o) : default(T);
  48. }
  49. }
  50. }