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

后端 未结 4 1771
[愿得一人]
[愿得一人] 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:36

    First of all, the example you provided has no Properties. It has private member variables. For properties, you would have something like:

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

    And then using reflection to get the values:

     public object GetVal(string propName)
     {
         var type = this.GetType();
         var propInfo = type.GetProperty(propName, BindingFlags.Instance);
         if(propInfo == null)
             throw new ArgumentException(String.Format(
                 "{0} is not a valid property of type: {1}",
                 propName, 
                 type.FullName));
    
         return propInfo.GetValue(this);
     }
    

    Keep in mind, though, that since you would already have access to the class and its properties (because you also have access to the method), it's much easier just to use the properties rather than do something fancy via Reflection.

提交回复
热议问题