我有以下课程:
public class MagicMetadata
{
public string DataLookupField { get; set; }
public string DataLookupTable { get; set; }
public List<string> Tags { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
和它的一个实例,让我们说:
MagicMetadata md = new MagicMetadata
{
DataLookupField = "Engine_Displacement",
DataLookupTable = "Vehicle_Options",
Tags = new List<String>{"a","b","c"}
}
Run Code Online (Sandbox Code Playgroud)
给定MagicMetadata实例,我需要为每个属性创建一个新对象,例如:
public class FormMetadataItem
{
public string FormFieldName { get; set; }
public string MetadataLabel { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
所以我正在按照c# foreach (对象中的属性)尝试这样的事情......有没有一种简单的方法可以做到这一点?
foreach (PropertyInfo propertyInfo in md.GetType().GetProperties())
{
new FormMetaData
{
FormFieldName = propertyInfo.Name,
MetadataLabel = propertyInfo.GetValue(metadata.Name) //This doesn't work
}
}
Run Code Online (Sandbox Code Playgroud)
我不明白的是我如何获得我正在循环的财产的价值。我根本不了解文档。为什么我需要将对象传递给它?什么对象?
PS我在这里查看了现有的答案,但没有看到明确的答案。
更新至:
foreach (PropertyInfo propertyInfo in md.GetType().GetProperties())
{
new FormMetaData
{
FormFieldName = propertyInfo.Name,
MetadataLabel = propertyInfo.GetValue(md) // <--
}
}
Run Code Online (Sandbox Code Playgroud)
PropertyInfo.GetValue()期望包含您试图获取其值的属性的对象实例。在您的
foreach循环中,该实例似乎是md.
还要注意C# 中property和之间的区别field。属性是具有get和/或的成员set:
class MyClass {
string MyProperty {get; set;} // This is a property
string MyField; // This is a field
}
Run Code Online (Sandbox Code Playgroud)
并且在反射时,您需要通过myObj.GetType().GetProperties()和myObj.GetType().GetFields()方法分别访问这些成员。
| 归档时间: |
|
| 查看次数: |
2888 次 |
| 最近记录: |