-
Notifications
You must be signed in to change notification settings - Fork 9
/
Copy pathReflectionUtility.cs
67 lines (57 loc) · 2.46 KB
/
ReflectionUtility.cs
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
57
58
59
60
61
62
63
64
65
66
67
using System;
using System.Reflection;
namespace Claws
{
internal static class ReflectionUtility
{
public static void SetPrivateMember(this object target, string memberName, object value)
{
var type = target.GetType();
FieldInfo targetField;
if ((targetField = type.GetField(memberName, BindingFlags.Instance | BindingFlags.NonPublic)) != null)
{
targetField.SetValue(target, value);
return;
}
PropertyInfo targetProperty;
if ((targetProperty = type.GetProperty(memberName, BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic)) != null)
{
targetProperty.SetValue(target, value);
}
}
public static void SetStaticMember(this Type type, string memberName, object value)
{
FieldInfo targetField;
if ((targetField = type.GetField(memberName, BindingFlags.Static | BindingFlags.NonPublic)) != null)
{
targetField.SetValue(null, value);
return;
}
PropertyInfo targetProperty;
if ((targetProperty = type.GetProperty(memberName, BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic)) != null)
{
targetProperty.SetValue(null, value);
}
}
public static T GetPrivateField<T>(this object target, string memberName) => target.GetPrivateField<T>(target.GetType(), memberName);
public static T GetPrivateField<T>(this object target, Type type, string memberName)
{
FieldInfo targetField;
if ((targetField = type.GetField(memberName, BindingFlags.Instance | BindingFlags.NonPublic)) != null)
{
return (T)targetField.GetValue(target);
}
PropertyInfo targetProperty;
if ((targetProperty = type.GetProperty(memberName, BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic)) != null)
{
return (T)targetProperty.GetValue(target);
}
return default;
}
public static void InvokePrivateMethod(this object target, string methodName, object[] methodParams)
{
var method = target.GetType().GetMethod(methodName, BindingFlags.Instance | BindingFlags.NonPublic);
method.Invoke(target, methodParams);
}
}
}