Property Name and need its value

后端 未结 5 992
萌比男神i
萌比男神i 2020-12-17 06:42

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?

5条回答
  •  渐次进展
    2020-12-17 07:36

    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);
    }
    

提交回复
热议问题