Use reflection to get the value of a property by name in a class instance

后端 未结 4 1774
[愿得一人]
[愿得一人] 2020-12-19 03:12

Lets say I have

class Person
{
    public Person(int age, string name)
    {
        Age = age;
        Name = name; 
    }
    public int Age{get;set}
             


        
4条回答
  •  野趣味
    野趣味 (楼主)
    2020-12-19 03:33

    ClassInstance.GetType.GetProperties() will get you your list of PropertyInfo objects. Spin through the PropertyInfos checking PropertyInfo.Name against propName. If they're equal then call the GetValue method of the PropertyInfo class to get its value.

    http://msdn.microsoft.com/en-us/library/system.reflection.propertyinfo.aspx

提交回复
热议问题