Question

I got two classes, and i want to use reflection.

public Class A
{
    public string aa { get; set; }
    public string bb { get; set; }
    ...
}

public Class B: A {}

when i try to get the Property of an B object i got no properties;

TypeInfo b = typeof(B).GetTypeInfo();
IEnumerable<PropertyInfo> pList = b.DeclaredProperties;  

pList is always null, maybe because i used "DeclaredProperties" instead of GetProproperties(), but in winRt i can't use it.

i've read this solution How to get properties of a class in WinRT but i can't use var properties = this.GetType().GetTypeInfo().GetRuntimeProperties(); because GetRuntimeProperties() is not recognized

Solution Found, doubts still remain

To get the property of an inherited class i need to get the RuntimeProperties in this way

IEnumerable<PropertyInfo> pList = typeof(B).GetRuntimeProperties();

ignoring the PropertyInfo, and it works too if i try to get the property of an A object

What are the differences between getType().GetTypeInfo() and getType().GetRuntimeProperties() while i'm reading the property of an A object?

Was it helpful?

Solution

public string aa;
public string bb;

These are not properties. Properties are defined such as:

public string Aa
{
    get;
    set;
}

For more information, look up the official documentation on MSDN.

Once you've made the corrections to your classes A and B, you will be able to use :

var classProperties = typeof(B).GetTypeInfo().DeclaredProperties;

For properties defined within the class B, and :

var allProperties = typeof(B).GetRuntimeProperties();

For properties that are defined within the class and in its inheritance tree; i.e. properties that are actually accessible at runtime (therefore the name of the method).

If you don't want to change the public fields to properties (but you definitely should), use the GetRuntimeFields method on typeof(B) and DeclaredMembers on typeof(B).GetTypeInfo() for similar behaviour.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top