简体   繁体   中英

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. Therefore, I thought the best way of doing this would be using reflection using 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? 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 . 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. See here for more detail on that. So either do this:

var fields = typeof(MaterialsStructure).GetFields();

Or change your class:

public class MaterialsStructure
{
    public ExistingProposedDescriptionStructure boundariesField { get; set;}
    public ExistingProposedDescriptionStructure ceilingsField { get; set;}
}

Now this will work:

var propeties = typeof(MaterialsStructure).GetProperties();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM