Get Property Value from PropertyInfo [duplicate]

2019-07-14 20:50发布

This question already has an answer here:

I have the following class:

public class MagicMetadata
{
  public string DataLookupField { get; set; }
  public string DataLookupTable { get; set; }
  public List<string> Tags { get; set; }
}

And an instance of it, let's say:

MagicMetadata md = new MagicMetadata
{
  DataLookupField = "Engine_Displacement",
  DataLookupTable = "Vehicle_Options",
  Tags = new List<String>{"a","b","c"}
}

Given the MagicMetadata instance, I need to create a new object for each property, e.g.:

public class FormMetadataItem 
{
  public string FormFieldName { get; set; }
  public string MetadataLabel { get; set; }
}

So I am trying something like this as per c# foreach (property in object)... Is there a simple way of doing this?

foreach (PropertyInfo propertyInfo in md.GetType().GetProperties())
{
   new FormMetaData
   {
     FormFieldName = propertyInfo.Name,
     MetadataLabel = propertyInfo.GetValue(metadata.Name) //This doesn't work
   }
}

What I don't understand is how I get the value for the property that I am looping through. I don't understand the documentation at all. Why do I need to pass it the object? What object?

P.S. I looked through the existing answers here, and I don't see a clear answer.

标签: c#
1条回答
▲ chillily
2楼-- · 2019-07-14 21:13

Update to:

foreach (PropertyInfo propertyInfo in md.GetType().GetProperties())
{
   new FormMetaData
   {
     FormFieldName = propertyInfo.Name,
     MetadataLabel = propertyInfo.GetValue(md) // <--
   }
}

PropertyInfo.GetValue() expects an instance of the object that contains the property whose value you're trying to get. In your foreach loop, that instance seems to be md.


Also note the distinction between property and field in C#. Properties are the members that have get and/or set:

class MyClass {
    string MyProperty {get; set;} // This is a property
    string MyField; // This is a field
}

And while reflecting, you need to access these members separately via the myObj.GetType().GetProperties() and myObj.GetType().GetFields() methods.

查看更多
登录 后发表回答