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

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

    You can do something like this:

    Person p = new Person( 10, "test" );
    
    IEnumerable<FieldInfo> fields = typeof( Person ).GetFields( BindingFlags.NonPublic | BindingFlags.Instance );
    
    string name = ( string ) fields.Single( f => f.Name.Equals( "name" ) ).GetValue( p );
    int age = ( int ) fields.Single( f => f.Name.Equals( "age" ) ).GetValue( p );
    

    Keep in mind since these are private instance fields you need to explicitly state the binding flags in order to get them via reflection.

    Edit:

    It seems you changed your sample from using fields to properties, so I'm just going to leave this here in case you change back again. :)

    0 讨论(0)
  • 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

    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2020-12-19 03:38

    I think this is the proper syntax...

    var myPropInfo = myType.GetProperty("MyProperty");
    var myValue = myPropInfo.GetValue(myInstance, null);
    
    0 讨论(0)
提交回复
热议问题