1 //
2 // http://code.google.com/p/servicestack/wiki/TypeSerializer
3 // ServiceStack.Text: .NET C# POCO Type Text Serializer.
4 //
5 // Authors:
6 //   Demis Bellot (demis.bellot@gmail.com)
7 //
8 // Copyright 2011 Liquidbit Ltd.
9 //
10 // Licensed under the same terms of ServiceStack: new BSD license.
11 //
12 using System;
13 using System.Reflection;
14 
15 #if !XBOX
16 using System.Linq.Expressions ;
17 #endif
18 namespace ServiceStack.Text.Reflection
19 {
20 	public static class StaticAccessors
21 	{
GetValueGetter(this PropertyInfo propertyInfo, Type type)22 		public static Func<object, object> GetValueGetter(this PropertyInfo propertyInfo, Type type)
23 		{
24 #if SILVERLIGHT || MONOTOUCH || XBOX
25 			var getMethodInfo = propertyInfo.GetGetMethod();
26 			if (getMethodInfo == null) return null;
27 			return x => getMethodInfo.Invoke(x, new object[0]);
28 #else
29 
30 			var instance = Expression.Parameter(typeof(object), "i");
31 			var convertInstance = Expression.TypeAs(instance, propertyInfo.DeclaringType);
32 			var property = Expression.Property(convertInstance, propertyInfo);
33 			var convertProperty = Expression.TypeAs(property, typeof(object));
34 			return Expression.Lambda<Func<object, object>>(convertProperty, instance).Compile();
35 #endif
36 		}
37 
GetValueGetter(this PropertyInfo propertyInfo)38 		public static Func<T, object> GetValueGetter<T>(this PropertyInfo propertyInfo)
39 		{
40 #if SILVERLIGHT || MONOTOUCH || XBOX
41 			var getMethodInfo = propertyInfo.GetGetMethod();
42 			if (getMethodInfo == null) return null;
43 			return x => getMethodInfo.Invoke(x, new object[0]);
44 #else
45 			var instance = Expression.Parameter(propertyInfo.DeclaringType, "i");
46 			var property = Expression.Property(instance, propertyInfo);
47 			var convert = Expression.TypeAs(property, typeof(object));
48 			return Expression.Lambda<Func<T, object>>(convert, instance).Compile();
49 #endif
50 		}
51 
52 #if !XBOX
GetValueSetter(this PropertyInfo propertyInfo)53 		public static Action<T, object> GetValueSetter<T>(this PropertyInfo propertyInfo)
54 		{
55 			if (typeof(T) != propertyInfo.DeclaringType)
56 			{
57 				throw new ArgumentException();
58 			}
59 
60 			var instance = Expression.Parameter(propertyInfo.DeclaringType, "i");
61 			var argument = Expression.Parameter(typeof(object), "a");
62 			var setterCall = Expression.Call(
63 				instance,
64 				propertyInfo.GetSetMethod(),
65 				Expression.Convert(argument, propertyInfo.PropertyType));
66 
67 			return Expression.Lambda<Action<T, object>>
68 			(
69 				setterCall, instance, argument
70 			).Compile();
71 		}
72 #endif
73 
74 	}
75 }
76 
77