Tips: Using Reflection to assign value intelligently
Published 26 Sept 2008, by Anytao
© 2008 Anytao.com, A fun world for making tech as art.
Usually, we map data from DB into models in for DAL. Of cource, we aslo encapsulate the models into Business Object(BO) or Domain Object(DO) for BLL. That's usual design affairs. In the case of design, different layers make a clear organize about business logic from data, service and so on.
However, it's unavoidable to pass value from Models to BOs to run business logic or pass value from BOs to Models to save data. This is unreasonable to handle many data transfer but necessary in this satuiation. How can we make it easy? Of course it is. Refelecting is a useful way to make data transfer easy for different CLR types value assignment.
Here is the way to get value from a instance by its propertyName:
{
return instance.GetType().InvokeMember(propertyName, BindingFlags.GetProperty,
null, instance, new object[] { });
}
{
instance.GetType().InvokeMember(propertyName, BindingFlags.SetProperty,
null, instance, new object[] { Convert.ChangeType(propertySetValue, propertySetValue.GetType()) });
}
{
List<PropertyInfo> list = new List<PropertyInfo>();
Type type = typeof(T);
object[] oProperties = type.GetProperties();
foreach (PropertyInfo pi in oProperties)
{
list.Add(pi);
}
return list;
}
{
//Your value assgin logic
}