Posted by 小寒 on 十二月 18, 2009
namespace System.Extension.Dynamic
{
public static class Dynamic
{
private static Dictionary<PropertyInfo, object> propertyGetters = new Dictionary<PropertyInfo, object>();
public static object Property(this object instance, string name)
{
var instanceType = instance.GetType();
var propertyInfo = instanceType.GetProperty(name);
if (propertyInfo == null) throw new InvalidOperationException();
if (!propertyInfo.CanRead) throw new InvalidOperationException();
object compiled;
if (!propertyGetters.TryGetValue(propertyInfo, out compiled))
{
var parameter = Expression.Parameter(typeof(object), "obj");
var convertParameter = Expression.Convert(parameter, instance.GetType());
var property = Expression.Property(convertParameter, propertyInfo);
var convertReturnValue = Expression.Convert(property, typeof(object));
var lambda = Expression.Lambda(convertReturnValue, parameter);
compiled = lambda.Compile();
propertyGetters.Add(propertyInfo, compiled);
}
return ((Func<object, object>)compiled)(instance);
}
}
}
C#
C#
0 Comments.