SuperJMN SuperJMN - 2 months ago 12
C# Question

Getting inherited public static field with Reflection in Portable Class Libraries

Within a Portable Class Library, I have 2 classes:

The parent

public class Parent
{
public string inherited;
public static string inheritedStatic;
}


And the child the derives from it

public class Child : Parent
{
public static string mine;
}


The problem is that I cannot get the inherited static field named "inheritedState", I just get the non-static ("inherited").

This is the code that I'm running:

class Program
{
static void Main(string[] args)
{
var childFields = typeof(Child).GetTypeInfo().GetRuntimeFields();

foreach (var fieldInfo in childFields)
{
Console.WriteLine(fieldInfo);
}
}
}


What should I do to get the inherited static field?
Thanks!

Answer

You could use:

public static FieldInfo[] DeclaredFields(TypeInfo type)
{
    var fields = new List<FieldInfo>();

    while (type != null)
    {
        fields.AddRange(type.DeclaredFields);

        Type type2 = type.BaseType;
        type = type2 != null ? type2.GetTypeInfo() : null;
    }

    return fields.ToArray();
}
Comments