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);
}
}