您的位置:首页 > 运维架构

Using Reflection and Expression to get Property with better performance.

2015-03-01 22:29 483 查看
I wrote a PropertyAccessor class for getting a property from a class using Reflection, yet it’s having better performance.

public class PropertyAccessor<TObject>
{
private Func<TObject, object> getter;
private Action<TObject, object> setter;

public PropertyAccessor(string propertyName)
{
var propertyInfo = typeof(TObject).GetProperty(propertyName);
if (null != propertyName)
{
var getMethodInfo = propertyInfo.GetGetMethod();
if (null != getMethodInfo)
{
var instance = Expression.Parameter(propertyInfo.DeclaringType, propertyName);
var property = Expression.Property(instance, propertyInfo);
// boxing/unboxing
var convert = Expression.TypeAs(property, typeof(object));
getter = (Func<TObject, object>)Expression.Lambda(convert, instance).Compile();
}

var setMethodInfo = propertyInfo.GetSetMethod();
if (null != setMethodInfo)
{
var instance = Expression.Parameter(propertyInfo.DeclaringType, propertyName);
var argument = Expression.Parameter(typeof(object), propertyName);
var setterCall = Expression.Call(
instance,
propertyInfo.GetSetMethod(),
// boxing/unboxing
Expression.Convert(argument, propertyInfo.PropertyType));
setter = (Action<TObject, object>)Expression.Lambda(setterCall, instance, argument).Compile();
}
}
}

public object GetValue(TObject obj)
{
// TODO; exception handling
return getter(obj);
}

public void SetValue(TObject obj, object newValue)
{
// TODO: exception handling
setter(obj, newValue);
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐