Instead of var fieldValue = field.ReflectedType.GetProperty(fieldName).GetValue(field.ReflectedType, null)
you should just have: var fieldValue = field.GetValue(o, null)
Notice you need to pass your instance of o
in. Really, you should do what L.B posted and find your property by name, or if you don't know the name, enumerate through through them via myType.GetProperties
Here's your code modified to work with properties:
private static void foo1<T>(T o)
{
var type = o.GetType();
var properties = type.GetProperties(BindingFlags.Public | BindingFlags.Instance | BindingFlags.NonPublic);
foo(properties, o);
}
private static void foo(PropertyInfo[] properties, object o)
{
foreach (PropertyInfo property in properties)
{
if (property.PropertyType.IsValueType)
{
var propertyValue = property.GetValue(o, null);
//do something with the property value?
}
}
}
EDIT: You may want to ensure that the property has a getter (see: How do you find only properties that have both a getter and setter?), or maybe that it's an auto-property (see: How to find out if a property is an auto-implemented property with reflection?) but I'm guessing this is not necessarily a requirement for you, probably just the proper usage of the GetValue
method or how to use reflection to inspect types.
EDIT: Here's the same code using fields if you still wish to use them:
private static void foo1<T>(T o)
{
var type = o.GetType();
var fields = type.GetFields(BindingFlags.Public | BindingFlags.Instance | BindingFlags.NonPublic);
foo(fields, o);
}
private static void foo(FieldInfo[] fields, object o)
{
foreach (FieldInfo field in fields)
{
if (field.FieldType.IsValueType)
{
var fieldValue = field.GetValue(o);
//do something with the field value?
}
}
}