我的任务是更新大量具有相同数据类型的记录,并且希望以这样的方式编写它,我不必找到每个类对象并手动执行它们。因此,我认为最好的方法是使用 PropertyInfo
进行反射。
在提出这个问题之前,我已经查看了以下内容;
Getting ALL the properties of an object How to get the list of properties of a class? https://www.codegrepper.com/code-examples/csharp/c%23+get+all+class+properties https://learn.microsoft.com/en-us/dotnet/api/system.type.getproperties?view=net-5.0
看看这个,表明我的方法是正确的,但我一生都没有得到结果。
代码如下
void Main()
{
var propeties = typeof(MaterialsStructure).GetProperties(BindingFlags.Public | BindingFlags.Static);
}
public class MaterialsStructure
{
public ExistingProposedDescriptionStructure boundariesField;
public ExistingProposedDescriptionStructure ceilingsField;
}
public class ExistingProposedDescriptionStructure
{
public string Existing { get; set; }
public string Proposed { get; set; }
public bool NotApplicable { get; set; }
public bool DontKnow { get; set; }
}
问题是,当我检查属性时,它在数组中有 0 个项目,而我原本期望它有两个 ExistingProposedDescriptionStructure
类型的属性。如果有人能告诉我我哪里出了问题,我将不胜感激。
最佳答案
您的MaterialsStructure
类没有属性,它有字段。请参阅here了解更多详情。所以要么这样做:
var fields = typeof(MaterialsStructure).GetFields();
或者改变你的类(class):
public class MaterialsStructure
{
public ExistingProposedDescriptionStructure boundariesField { get; set;}
public ExistingProposedDescriptionStructure ceilingsField { get; set;}
}
现在这可以工作了:
var propeties = typeof(MaterialsStructure).GetProperties();
关于c# - 使用反射获取类属性信息不返回任何内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66064505/