-
Notifications
You must be signed in to change notification settings - Fork 483
/
Copy pathReflectionExtensions.cs
232 lines (203 loc) · 8.57 KB
/
ReflectionExtensions.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
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
// Copyright 2005-2015 Giacomo Stelluti Scala & Contributors. All rights reserved. See License.md in the project root for license information.
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using CommandLine.Infrastructure;
using CommandLine.Text;
using CSharpx;
namespace CommandLine.Core
{
static class ReflectionExtensions
{
public static IEnumerable<T> GetSpecifications<T>(this Type type, Func<PropertyInfo, T> selector)
{
return from pi in type.FlattenHierarchy().SelectMany(x => x.GetTypeInfo().GetProperties())
let attrs = pi.GetCustomAttributes(true)
where
attrs.OfType<OptionAttribute>().Any() ||
attrs.OfType<ValueAttribute>().Any()
group pi by pi.Name into g
select selector(g.First());
}
public static Maybe<VerbAttribute> GetVerbSpecification(this Type type)
{
return
(from attr in
type.FlattenHierarchy().SelectMany(x => x.GetTypeInfo().GetCustomAttributes(typeof(VerbAttribute), true))
let vattr = (VerbAttribute)attr
select vattr)
.SingleOrDefault()
.ToMaybe();
}
public static Maybe<Tuple<PropertyInfo, UsageAttribute>> GetUsageData(this Type type)
{
return
(from pi in type.FlattenHierarchy().SelectMany(x => x.GetTypeInfo().GetProperties())
let attrs = pi.GetCustomAttributes(typeof(UsageAttribute), true)
where attrs.Any()
select Tuple.Create(pi, (UsageAttribute)attrs.First()))
.SingleOrDefault()
.ToMaybe();
}
private static IEnumerable<Type> FlattenHierarchy(this Type type)
{
if (type == null)
{
yield break;
}
yield return type;
foreach (var @interface in type.SafeGetInterfaces())
{
yield return @interface;
}
foreach (var @interface in FlattenHierarchy(type.GetTypeInfo().BaseType))
{
yield return @interface;
}
}
private static IEnumerable<Type> SafeGetInterfaces(this Type type)
{
return type == null ? Enumerable.Empty<Type>() : type.GetTypeInfo().GetInterfaces();
}
public static TargetType ToTargetType(this Type type)
{
return type == typeof(bool)
? TargetType.Switch
: type == typeof(string)
? TargetType.Scalar
: type.IsArray || typeof(IEnumerable).GetTypeInfo().IsAssignableFrom(type)
? TargetType.Sequence
: TargetType.Scalar;
}
public static IEnumerable<Error> SetProperties<T>(
this T instance,
IEnumerable<SpecificationProperty> specProps,
Func<SpecificationProperty, bool> predicate,
Func<SpecificationProperty, object> selector)
{
return specProps.Where(predicate).SelectMany(specProp => specProp.SetValue(instance, selector(specProp)));
}
private static IEnumerable<Error> SetValue<T>(this SpecificationProperty specProp, T instance, object value)
{
try
{
specProp.Property.SetValue(instance, value, null);
return Enumerable.Empty<Error>();
}
catch (TargetInvocationException e)
{
return new[] { new SetValueExceptionError(specProp.Specification.FromSpecification(), e.InnerException, value) };
}
catch (ArgumentException e)
{
var argEx = new ArgumentException(InvalidAttributeConfigurationError.ErrorMessage, e);
return new[] { new SetValueExceptionError(specProp.Specification.FromSpecification(), argEx, value) };
}
catch (Exception e)
{
return new[] { new SetValueExceptionError(specProp.Specification.FromSpecification(), e, value) };
}
}
public static object CreateEmptyArray(this Type type)
{
return Array.CreateInstance(type, 0);
}
public static object GetDefaultValue(this Type type)
{
return type.IsValueType ? Activator.CreateInstance(type) : null;
}
public static bool IsMutable(this Type type)
{
if(type == typeof(object))
return true;
// Find all inherited defined properties and fields on the type
var inheritedTypes = type.GetTypeInfo().FlattenHierarchy().Select(i => i.GetTypeInfo());
foreach (var inheritedType in inheritedTypes)
{
if (
inheritedType.GetTypeInfo().GetProperties(BindingFlags.Public | BindingFlags.Instance).Any(p => p.CanWrite) ||
inheritedType.GetTypeInfo().GetFields(BindingFlags.Public | BindingFlags.Instance).Any()
)
{
return true;
}
}
return false;
}
public static bool HasParameterlessConstructor(this Type type)
{
return type.GetTypeInfo().GetConstructor(Type.EmptyTypes) != null;
}
public static object CreateDefaultForImmutable(this Type type)
{
if (type.GetTypeInfo().IsGenericType && type.GetTypeInfo().GetGenericTypeDefinition() == typeof(IEnumerable<>))
{
return type.GetTypeInfo().GetGenericArguments()[0].CreateEmptyArray();
}
return type.GetDefaultValue();
}
public static object AutoDefault(this Type type)
{
if (type.IsMutable() && type.HasParameterlessConstructor())
{
return Activator.CreateInstance(type);
}
var ctorTypes = type.GetSpecifications(pi => pi.PropertyType).ToArray();
return ReflectionHelper.CreateDefaultImmutableInstance(type, ctorTypes);
}
public static TypeInfo ToTypeInfo(this Type type)
{
return TypeInfo.Create(type);
}
public static object StaticMethod(this Type type, string name, params object[] args)
{
return type.GetTypeInfo().InvokeMember(
name,
BindingFlags.InvokeMethod | BindingFlags.Public | BindingFlags.Static,
null,
null,
args);
}
public static object StaticProperty(this Type type, string name)
{
return type.GetTypeInfo().InvokeMember(
name,
BindingFlags.GetProperty | BindingFlags.Public | BindingFlags.Static,
null,
null,
new object[] { });
}
public static object InstanceProperty(this Type type, string name, object target)
{
return type.GetTypeInfo().InvokeMember(
name,
BindingFlags.GetProperty | BindingFlags.Public | BindingFlags.Instance,
null,
target,
new object[] { });
}
public static bool IsPrimitiveEx(this Type type)
{
return
(type.GetTypeInfo().IsValueType && type != typeof(Guid))
|| type.GetTypeInfo().IsPrimitive
|| new [] {
typeof(string)
,typeof(decimal)
,typeof(DateTime)
,typeof(DateTimeOffset)
,typeof(TimeSpan)
}.Contains(type)
|| Convert.GetTypeCode(type) != TypeCode.Object;
}
public static bool IsCustomStruct(this Type type)
{
var isStruct = type.GetTypeInfo().IsValueType && !type.GetTypeInfo().IsPrimitive && !type.GetTypeInfo().IsEnum && type != typeof(Guid);
if (!isStruct) return false;
var ctor = type.GetTypeInfo().GetConstructor(new[] { typeof(string) });
return ctor != null;
}
}
}