How to get a property value using reflection

前端 未结 2 392
陌清茗
陌清茗 2020-11-28 14:19

I have the following code:

FieldInfo[] fieldInfos;
fieldInfos = GetType().GetFields(BindingFlags.NonPublic | BindingFlags.Instance);

What I

相关标签:
2条回答
  • 2020-11-28 14:38

    Something like this should work:

    var value = (string)GetType().GetProperty("SomeProperty").GetValue(this, null);
    
    0 讨论(0)
  • 2020-11-28 14:56

    Try the GetProperties method, it should get you the property, instead of fields.

    To retrieve the value, do something like this:

    object foo = ...;
    object propertyValue = foo.GetType().GetProperty("PropertyName").GetValue(foo, null);
    

    This is using GetProperty, which returns just one PropertyInfo object, rather than an array of them. We then call GetValue, which takes a parameter of the object to retrieve the value from (the PropertyInfo is specific to the type, not the instance). The second parameter to GetValue is an array of indexers, for index properties, and I'm assuming the property you're interested in isn't an indexed property. (An indexed property is what lets you do list[14] to retrieve the 14th element of a list.)

    0 讨论(0)
提交回复
热议问题