[英]Using Reflection to Get Class Property Information returning nothing
I have been tasked with updating a large number of records that all have the same data type and want to write this in such a way I don't have to find every class object and do them manually.我的任务是更新大量具有相同数据类型的记录,并希望以这样的方式编写它,我不必找到每个 class object 并手动执行它们。 Therefore, I thought the best way of doing this would be using reflection using PropertyInfo
.因此,我认为最好的方法是使用PropertyInfo
进行反射。
Prior to asking this question I have looked at the following;在问这个问题之前,我已经看过以下内容;
Getting ALL the properties of an object How to get the list of properties of a class? 获取 object 的所有属性如何获取 class 的属性列表? https://www.codegrepper.com/code-examples/csharp/c%23+get+all+class+properties https://docs.microsoft.com/en-us/dotnet/api/system.type.getproperties?view=net-5.0 https://www.codegrepper.com/code-examples/csharp/c%23+get+all+class+properties https://docs.microsoft.com/en-us/dotnet/api/system.type.getproperties ?view=net-5.0
looking at this, suggested I'm on the right approach, but for the life of me Im not getting the results.看着这个,建议我采用正确的方法,但对于我的生活,我没有得到结果。
The code is as follows代码如下
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; }
}
The problem is that when I inspect properties it has 0 items in the array, where I would have expected it to have two properties of type ExistingProposedDescriptionStructure
.问题是,当我检查属性时,它在数组中有 0 个项目,我原以为它有两个ExistingProposedDescriptionStructure
类型的属性。 I would be grateful if someone could show me where I have gone wrong here.如果有人能告诉我我在哪里出错了,我将不胜感激。
Your MaterialsStructure
class doesn't have properties, it has fields.您的MaterialsStructure
class 没有属性,它有字段。 See here for more detail on that.有关详细信息,请参见此处。 So either do this:所以要么这样做:
var fields = typeof(MaterialsStructure).GetFields();
Or change your class:或更改您的 class:
public class MaterialsStructure
{
public ExistingProposedDescriptionStructure boundariesField { get; set;}
public ExistingProposedDescriptionStructure ceilingsField { get; set;}
}
Now this will work:现在这将起作用:
var propeties = typeof(MaterialsStructure).GetProperties();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.