GetFields Derived Type

I am trying to reflect fields in a derived type, but it returns the fields of the base type.

public class basetype { string basevar; } public class derivedtype : basetype { string derivedvar; } 

In some function:

 derivedtype derived = new derivedtype(); FieldInfo[] fields = derived.GetType().GetFields(); 

This will cause basevar to return, but not outputvar. I tried all the various bindings and it doesn't seem to matter.

In addition, I do this in ASP.NET in App_Code, where basevar is defined in App_Code, and nativevar is a user control defined in App_Controls where types are not in scope.

+4
source share
2 answers

As is, this will not return anything, since the default binding is only for public fields.

As well, the derived type is not inferred from the base type

FROM

 FieldInfo[] fields = derived.GetType().GetFields(BindingFlags.NonPublic | BindingFlags.Instance); 

It returns outputvar. I just checked LINQPad.

If I change the derived type to be obtained from the base type, then I can get both fields with:

 FieldInfo[] fields = derived.GetType().GetFields(BindingFlags.NonPublic | BindingFlags.Instance).Concat(derived.GetType().BaseType.GetFields(BindingFlags.NonPublic | BindingFlags.Instance)).ToArray(); 
+7
source

The reflection is a bit odd.

If members are public, they all display the entire hierarchy.

If members are not publicly available, you need to specify BindingFlags.NonPublic, and you will receive only those elements that are of type. Inherited items are not displayed. If you want to see all non-public type members, you will have to go up to the inheritance chain.

+2
source

All Articles