How can I get the value of a string property via Reflection?

前端 未结 9 1581
日久生厌
日久生厌 2020-11-30 04:46
public class Foo
{
   public string Bar {get; set;}
}

How do I get the value of Bar, a string property, via reflection? The following code will thr

相关标签:
9条回答
  • 2020-11-30 05:42

    You can just get the property by name:

    Foo f = new Foo();
    f.Bar = "Jon Skeet is god.";
    
    var barProperty = f.GetType().GetProperty("Bar");
    string s = barProperty.GetValue(f,null) as string;
    

    Regarding the follow up question: Indexers will always be named Item and have arguments on the getter. So

    Foo f = new Foo();
    f.Bar = "Jon Skeet is god.";
    
    var barProperty = f.GetType().GetProperty("Item");
    if (barProperty.GetGetMethod().GetParameters().Length>0)
    {
        object value = barProperty.GetValue(f,new []{1/* indexer value(s)*/});
    }
    
    0 讨论(0)
  • 2020-11-30 05:42
    PropertyInfo propInfo = f.GetType().GetProperty("Bar");
    object[] obRetVal = new Object[0];
    string bar = propInfo.GetValue(f,obRetVal) as string;
    
    0 讨论(0)
  • 2020-11-30 05:43

    the getvalue with object and null worked great for me. Thanks for the posts.

    Context: Looping through all properties in an MVC model for New Hires and determining their form posted values:

    newHire => the Model, with many properties, whose posted form values I want to write individually to a set of database records

    foreach(var propertyValue in newHire.GetProperties())
    {
    string propName = propertyValue.Name;
    
    string postedValue = newHire.GetType().GetProperty(propName).GetValue(newHire, null).ToString();
    
    }
    
    0 讨论(0)
提交回复
热议问题