How do I get the value of a MemberInfo
object? .Name
returns the name of the variable, but I need the value.
I think you can do this with
Jon's answer is ideal - just one observation: as part of general design, I would:
The upshot of these two is that generally you only need to reflect against public properties (you shouldn't be calling methods unless you know what they do; property getters are expected to be idempotent [lazy loading aside]). So for a PropertyInfo
this is just prop.GetValue(obj, null);
.
Actually, I'm a big fan of System.ComponentModel
, so I would be tempted to use:
foreach(PropertyDescriptor prop in TypeDescriptor.GetProperties(obj))
{
Console.WriteLine("{0}={1}", prop.Name, prop.GetValue(obj));
}
or for a specific property:
PropertyDescriptor prop = TypeDescriptor.GetProperties(obj)["SomeProperty"];
Console.WriteLine("{0}={1}", prop.Name, prop.GetValue(obj));
One advantage of System.ComponentModel
is that it will work with abstracted data models, such as how a DataView
exposes columns as virtual properties; there are other tricks too (like performance tricks).