Possible Duplicate:
How can I read the properties of a C# class dynamically?
I have to get values of class members using strings of their names only. I think I have to use Reflection but I am not realy sure how to. Can you help me?
MemberInfo member = typeof(MyClass).GetMember("membername");
GetMember reference.
If you know type of member you're looking for, you can use .GetMethod
, .GetField
, .GetProperty
, etc.
If you don't know the type you are working with:
var myobject = someobject;
string membername = "somemember";
MemberInfo member = myobject.GetType().GetMember(membername);
Different member types have different means to getting the value. For a property you would do:
var myobject = someobject;
string propertyname = "somemember";
PropertyInfo property = myobject.GetType().GetProperty(membername);
object value = property.GetValue(myobject, null);
public class Foo
{
public string A { get; set; }
}
public class Example
{
public void GetPropertyValueExample()
{
Foo f = new Foo();
f.A = "Example";
var val = f.GetType().GetProperty("A").GetValue(f, null);
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With