从PropertyInfo获取属性

从PropertyInfo获取属性

本文介绍了从PropertyInfo获取属性值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下课程:

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"}
}

鉴于 MagicMetadata 实例,我需要为每个属性创建一个新对象,例如:

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; }
}

所以我正在尝试按照

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.我在这里浏览了现有的答案,但看不到明确的答案.

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

推荐答案

更新至:

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

PropertyInfo.GetValue()期望对象的实例包含您要获取其值的属性.在你的 foreach 循环,该实例似乎是 md .

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

还请注意C#中的属性 field 之间的区别.属性是具有 get 和/或 set 的成员:

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
}

在反思的同时,您需要通过 myObj.GetType().GetProperties() myObj.GetType().GetFields() 方法.

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

这篇关于从PropertyInfo获取属性值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-05 12:14