C# Reflection Utility
October 4, 2011 at 8:52 PM
—
dsoltesz
Here is a reflection utility helper class that will allow you to get a property from a object at runtime. This utility will also support nested properties via the "." operator.
Using the class is pretty easy
var myObject = (IMyObjectType)ReflectionUtility.GetObjectProperty(item, "Model");
public static class ReflectionUtility
{
public static object GetObjectProperty(object item, string property)
{
if (item == null)
return null;
var dotIdx = property.IndexOf('.');
if (dotIdx > 0)
{
object obj = GetObjectProperty(item, property.Substring(0, dotIdx));
return GetObjectProperty(obj, property.Substring(dotIdx + 1));
}
PropertyInfo propInfo = null;
var objectType = item.GetType();
while (propInfo == null && objectType != null)
{
propInfo = objectType.GetProperty(property,
BindingFlags.Public
| BindingFlags.Instance
| BindingFlags.DeclaredOnly);
objectType = objectType.BaseType;
}
if (propInfo != null)
return propInfo.GetValue(item, null);
var fieldInfo = item.GetType().GetField(property,
BindingFlags.Public | BindingFlags.Instance);
return fieldInfo != null ? fieldInfo.GetValue(item) : null;
}
}
8d820c7f-85e2-4a05-bb16-df14c1fb5f9b|0|.0
Posted in:
Tags: c#