How can I get field's value if it's defined as automatic property?
I don't know why but first time I encounter such simple task with such an unexplained method called GetValue
which don't work as I want to and usually throws all kinds of exceptions instead of doing its original simple job..
Some code for example:
Class A
{
public int Age { get; set;}
}
Now assume that after reflection I hold A instances' fields in structure of FiledInfo[] .
Now I have found the relevant fieldInfo in the above array and his name is :
{Int32 k__BackingField} sound strange,anyway..
How do I use GetValue() in order to get the int value? As I said I tried many things..
EDIT: (this is partial simplified code - don't get mad)
private static string foo1<T>(T o)
{
var type = o.GetType();
var fields = type.GetFields(BindingFlags.Public | BindingFlags.Instance | BindingFlags.NonPublic);
....
foo(fields);
}
}
private static void foo(FieldInfo[] fields)
{
foreach (FieldInfo field in fields)
{
if (field.FieldType.IsValueType)
{
var fieldNameLength = field.Name.IndexOf(">") - (field.Name.IndexOf("<")+1);
var fieldName = field.Name.Substring(field.Name.IndexOf("<")+1, fieldNameLength);
var fieldValue = field.ReflectedType.GetProperty(fieldName).GetValue(field.ReflectedType, null)
}
}
}