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