Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I have a name of a property and need to find its value within a Class, what is the fastest way of getting to this value?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
188 views
Welcome To Ask or Share your Answers For Others

1 Answer

I am making the assumption that you have the name of the property in runtime; not while coding...

Let's assume your class is called TheClass and it has a property called TheProperty:

object GetThePropertyValue(object instance)
{
    Type type = instance.GetType();
    PropertyInfo propertyInfo = type.GetProperty("TheProperty");
    return propertyInfo.GetValue(instance, null);
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...