-
Notifications
You must be signed in to change notification settings - Fork 774
Expand file tree
/
Copy pathReflectionUtil.cs
More file actions
63 lines (49 loc) · 2.02 KB
/
ReflectionUtil.cs
File metadata and controls
63 lines (49 loc) · 2.02 KB
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
namespace Python.Runtime;
using System;
using System.Reflection;
static class ReflectionUtil
{
public static MethodInfo? GetBaseGetMethod(this PropertyInfo property, bool nonPublic)
{
if (property is null) throw new ArgumentNullException(nameof(property));
Type baseType = property.DeclaringType.BaseType;
BindingFlags bindingFlags = property.GetBindingFlags();
while (baseType is not null)
{
var baseProperty = baseType.GetProperty(property.Name, bindingFlags | BindingFlags.DeclaredOnly);
var accessor = baseProperty?.GetGetMethod(nonPublic);
if (accessor is not null)
return accessor;
baseType = baseType.BaseType;
}
return null;
}
public static MethodInfo? GetBaseSetMethod(this PropertyInfo property, bool nonPublic)
{
if (property is null) throw new ArgumentNullException(nameof(property));
Type baseType = property.DeclaringType.BaseType;
BindingFlags bindingFlags = property.GetBindingFlags();
while (baseType is not null)
{
var baseProperty = baseType.GetProperty(property.Name, bindingFlags | BindingFlags.DeclaredOnly);
var accessor = baseProperty?.GetSetMethod(nonPublic);
if (accessor is not null)
return accessor;
baseType = baseType.BaseType;
}
return null;
}
public static BindingFlags GetBindingFlags(this PropertyInfo property)
{
var accessor = property.GetMethod ?? property.SetMethod;
BindingFlags flags = default;
flags |= accessor.IsStatic ? BindingFlags.Static : BindingFlags.Instance;
flags |= accessor.IsPublic ? BindingFlags.Public : BindingFlags.NonPublic;
return flags;
}
public static Type? TryGetGenericDefinition(this Type type)
{
if (type is null) throw new ArgumentNullException(nameof(type));
return type.IsConstructedGenericType ? type.GetGenericTypeDefinition() : null;
}
}