forked from reactiveui/ReactiveUI
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathReflection.cs
More file actions
342 lines (276 loc) · 12.9 KB
/
Reflection.cs
File metadata and controls
342 lines (276 loc) · 12.9 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
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
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
using System;
using System.Collections.Generic;
using System.Diagnostics.Contracts;
using System.Linq;
using System.Linq.Expressions;
using System.Reactive.Linq;
using System.Reflection;
using ReactiveUI;
using Splat;
namespace ReactiveUI
{
public static class Reflection
{
static readonly MemoizingMRUCache<Tuple<Type, string>, Func<object, object>> propReaderCache =
new MemoizingMRUCache<Tuple<Type, string>, Func<object, object>>((x,_) => {
var fi = x.Item1.GetRuntimeFields()
.FirstOrDefault(y => !y.IsStatic && y.Name == x.Item2);
if (fi != null) {
return (fi.GetValue);
}
var pi = x.Item1.GetRuntimeProperties()
.FirstOrDefault(y => !y.IsStatic() && y.Name == x.Item2);
if (pi != null) {
return (y => pi.GetValue(y, null));
}
return null;
}, RxApp.BigCacheLimit);
static readonly MemoizingMRUCache<Tuple<Type, string>, Action<object, object>> propWriterCache =
new MemoizingMRUCache<Tuple<Type, string>, Action<object, object>>((x,_) => {
var fi = x.Item1.GetRuntimeFields()
.FirstOrDefault(y => y.IsPublic && !y.IsStatic && y.Name == x.Item2);
if (fi != null) {
return (fi.SetValue);
}
var pi = x.Item1.GetRuntimeProperties()
.FirstOrDefault(y => !y.IsStatic() && y.Name == x.Item2);
if (pi != null) {
return ((y,v) => pi.SetValue(y, v, null));
}
return null;
}, RxApp.BigCacheLimit);
public static string SimpleExpressionToPropertyName<TObj, TRet>(Expression<Func<TObj, TRet>> property)
{
Contract.Requires(property != null);
string propName = null;
try {
var propExpr = property.Body as MemberExpression;
if (propExpr.Expression.NodeType != ExpressionType.Parameter) {
throw new ArgumentException("Property expression must be of the form 'x => x.SomeProperty'");
}
propName = propExpr.Member.Name;
} catch (NullReferenceException) {
throw new ArgumentException("Property expression must be of the form 'x => x.SomeProperty'");
}
return propName;
}
public static string[] ExpressionToPropertyNames<TObj, TRet>(Expression<Func<TObj, TRet>> property)
{
var ret = new List<string>();
var current = property.Body;
while(current.NodeType != ExpressionType.Parameter) {
// This happens when a value type gets boxed
if (current.NodeType == ExpressionType.Convert || current.NodeType == ExpressionType.ConvertChecked) {
var ue = (UnaryExpression) current;
current = ue.Operand;
continue;
}
if (current.NodeType != ExpressionType.MemberAccess) {
throw new ArgumentException("Property expression must be of the form 'x => x.SomeProperty.SomeOtherProperty'");
}
var me = (MemberExpression)current;
ret.Insert(0, me.Member.Name);
current = me.Expression;
}
return ret.ToArray();
}
public static Type[] ExpressionToPropertyTypes<TObj, TRet>(Expression<Func<TObj, TRet>> property)
{
var current = property.Body;
while(current.NodeType != ExpressionType.Parameter) {
// This happens when a value type gets boxed
if (current.NodeType == ExpressionType.Convert || current.NodeType == ExpressionType.ConvertChecked) {
var ue = (UnaryExpression) current;
current = ue.Operand;
continue;
}
if (current.NodeType != ExpressionType.MemberAccess) {
throw new ArgumentException("Property expression must be of the form 'x => x.SomeProperty.SomeOtherProperty'");
}
var me = (MemberExpression)current;
current = me.Expression;
}
var startingType = ((ParameterExpression) current).Type;
var propNames = ExpressionToPropertyNames(property);
return GetTypesForPropChain(startingType, propNames);
}
public static Type[] GetTypesForPropChain(Type startingType, string[] propNames)
{
return propNames.Aggregate(new List<Type>(new[] {startingType}), (acc, x) => {
var type = acc.Last();
var pi = type.GetRuntimeProperties().FirstOrDefault(y => y.Name == x);
if (pi != null) {
acc.Add(pi.PropertyType);
return acc;
}
var fi = type.GetRuntimeFields().FirstOrDefault(y => y.Name == x);
if (fi != null) {
acc.Add(fi.FieldType);
return acc;
}
throw new ArgumentException("Property expression must be of the form 'x => x.SomeProperty.SomeOtherProperty'");
}).Skip(1).ToArray();
}
public static Func<TObj, object> GetValueFetcherForProperty<TObj>(string propName)
{
var ret = GetValueFetcherForProperty(typeof(TObj), propName);
return x => (TObj) ret(x);
}
public static Func<object, object> GetValueFetcherForProperty(Type type, string propName)
{
Contract.Requires(type != null);
Contract.Requires(propName != null);
lock (propReaderCache) {
return propReaderCache.Get(Tuple.Create(type, propName));
}
}
public static Func<object, object> GetValueFetcherOrThrow(Type type, string propName)
{
var ret = GetValueFetcherForProperty(type, propName);
if (ret == null) {
throw new ArgumentException(String.Format("Type '{0}' must have a property '{1}'", type, propName));
}
return ret;
}
public static Action<object, object> GetValueSetterForProperty(Type type, string propName)
{
Contract.Requires(type != null);
Contract.Requires(propName != null);
lock (propReaderCache) {
return propWriterCache.Get(Tuple.Create(type, propName));
}
}
public static Action<object, object> GetValueSetterOrThrow(Type type, string propName)
{
var ret = GetValueSetterForProperty(type, propName);
if (ret == null) {
throw new ArgumentException(String.Format("Type '{0}' must have a property '{1}'", type, propName));
}
return ret;
}
public static bool TryGetValueForPropertyChain<TValue>(out TValue changeValue, object current, string[] propNames)
{
foreach (var propName in propNames.SkipLast(1)) {
if (current == null) {
changeValue = default(TValue);
return false;
}
current = GetValueFetcherOrThrow(current.GetType(), propName)(current);
}
if (current == null) {
changeValue = default(TValue);
return false;
}
changeValue = (TValue) GetValueFetcherOrThrow(current.GetType(), propNames.Last())(current);
return true;
}
public static bool TryGetAllValuesForPropertyChain(out IObservedChange<object, object>[] changeValues, object current, string[] propNames)
{
int currentIndex = 0;
changeValues = new IObservedChange<object,object>[propNames.Length];
foreach (var propName in propNames.SkipLast(1)) {
if (current == null) {
changeValues[currentIndex] = null;
return false;
}
var box = new ObservedChange<object, object> { Sender = current, PropertyName = propName };
current = GetValueFetcherOrThrow(current.GetType(), propName)(current);
box.Value = current;
changeValues[currentIndex] = box;
currentIndex++;
}
if (current == null) {
changeValues[currentIndex] = null;
return false;
}
changeValues[currentIndex] = new ObservedChange<object, object> {
Sender = current,
PropertyName = propNames.Last(),
Value = GetValueFetcherOrThrow(current.GetType(), propNames.Last())(current)
};
return true;
}
public static bool SetValueToPropertyChain<TValue>(object target, string[] propNames, TValue value, bool shouldThrow = true)
{
foreach (var propName in propNames.SkipLast(1)) {
var getter = shouldThrow ?
GetValueFetcherOrThrow(target.GetType(), propName) :
GetValueFetcherForProperty(target.GetType(), propName);
target = getter(target);
}
if (target == null) return false;
var setter = shouldThrow ?
GetValueSetterOrThrow(target.GetType(), propNames.Last()) :
GetValueSetterForProperty(target.GetType(), propNames.Last());
if (setter == null) return false;
setter(target, value);
return true;
}
static readonly MemoizingMRUCache<string, Type> typeCache = new MemoizingMRUCache<string, Type>((type,_) => {
return Type.GetType(type, false);
}, 20);
public static Type ReallyFindType(string type, bool throwOnFailure)
{
lock (typeCache) {
var ret = typeCache.Get(type);
if (ret != null || !throwOnFailure) return ret;
throw new TypeLoadException();
}
}
public static Type GetEventArgsTypeForEvent(Type type, string eventName)
{
var ti = type;
var ei = ti.GetRuntimeEvent(eventName);
if (ei == null) {
throw new Exception(String.Format("Couldn't find {0}.{1}", type.FullName, eventName));
}
// Find the EventArgs type parameter of the event via digging around via reflection
var eventArgsType = ei.EventHandlerType.GetRuntimeMethods().First(x => x.Name == "Invoke").GetParameters()[1].ParameterType;
return eventArgsType;
}
internal static IObservable<TProp> ViewModelWhenAnyValue<TView, TViewModel, TProp>(TViewModel viewModel, TView view, Expression<Func<TViewModel, TProp>> property)
where TView : IViewFor
where TViewModel : class
{
return view.WhenAnyValue(x => x.ViewModel)
.Where(x => x != null)
.Select(x => ((TViewModel)x).WhenAnyValue(property))
.Switch();
}
internal static IObservable<object> ViewModelWhenAnyValueDynamic<TView, TViewModel>(TViewModel viewModel, TView view, string[] property)
where TView : IViewFor
where TViewModel : class
{
return view.WhenAny(x => x.ViewModel, x => x.Value)
.Where(x => x != null)
.Select(x => property.Length == 0 ? Observable.Return(x) : ((TViewModel)x).WhenAnyDynamic(property, y => y.Value))
.Switch();
}
internal static string[] getDefaultViewPropChain(object view, string[] vmPropChain)
{
var vmPropertyName = vmPropChain.Last();
var getter = GetValueFetcherForProperty(view.GetType(), vmPropertyName);
if (getter == null) {
throw new Exception(String.Format("Tried to bind to control but it wasn't present on the object: {0}.{1}",
view.GetType().FullName, vmPropertyName));
}
var control = getter(view);
if (control == null) {
throw new Exception(String.Format("Tried to bind to control but it was null: {0}.{1}", view.GetType().FullName,
vmPropertyName));
}
var defaultProperty = DefaultPropertyBinding.GetPropertyForControl(control);
if (defaultProperty == null) {
throw new Exception(String.Format("Couldn't find a default property for type {0}", control.GetType()));
}
return new[] {vmPropertyName, defaultProperty};
}
}
public static class ReflectionExtensions
{
public static bool IsStatic(this PropertyInfo This)
{
return (This.GetMethod ?? This.SetMethod).IsStatic;
}
}
}