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

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

提交回复
热议问题