forked from ServiceStack/ServiceStack
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPropertyInvoker.cs
More file actions
69 lines (57 loc) · 2.49 KB
/
PropertyInvoker.cs
File metadata and controls
69 lines (57 loc) · 2.49 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
using System;
using System.Linq.Expressions;
using System.Reflection;
namespace ServiceStack.Common.Support
{
public delegate void PropertySetterDelegate(object instance, object value);
public delegate object PropertyGetterDelegate(object instance);
public static class PropertyInvoker
{
public static PropertySetterDelegate GetPropertySetterFn(this PropertyInfo propertyInfo)
{
var propertySetMethod = propertyInfo.GetSetMethod();
if (propertySetMethod == null) return null;
#if MONOTOUCH || SILVERLIGHT || XBOX
return (o, convertedValue) =>
{
propertySetMethod.Invoke(o, new[] { convertedValue });
return;
};
#else
var instance = Expression.Parameter(typeof(object), "i");
var argument = Expression.Parameter(typeof(object), "a");
var instanceParam = Expression.Convert(instance, propertyInfo.DeclaringType);
var valueParam = Expression.Convert(argument, propertyInfo.PropertyType);
var setterCall = Expression.Call(instanceParam, propertyInfo.GetSetMethod(), valueParam);
return Expression.Lambda<PropertySetterDelegate>(setterCall, instance, argument).Compile();
#endif
}
public static PropertyGetterDelegate GetPropertyGetterFn(this PropertyInfo propertyInfo)
{
var getMethodInfo = propertyInfo.GetGetMethod();
if (getMethodInfo == null) return null;
#if MONOTOUCH || SILVERLIGHT || XBOX
return o => propertyInfo.GetGetMethod().Invoke(o, new object[] { });
#else
try
{
var oInstanceParam = Expression.Parameter(typeof(object), "oInstanceParam");
var instanceParam = Expression.Convert(oInstanceParam, propertyInfo.DeclaringType);
var exprCallPropertyGetFn = Expression.Call(instanceParam, getMethodInfo);
var oExprCallPropertyGetFn = Expression.Convert(exprCallPropertyGetFn, typeof(object));
var propertyGetFn = Expression.Lambda<PropertyGetterDelegate>
(
oExprCallPropertyGetFn,
oInstanceParam
).Compile();
return propertyGetFn;
}
catch (Exception ex)
{
Console.Write(ex.Message);
throw;
}
#endif
}
}
}