Getting inherited public static field with Reflection in Portable Class Libraries

464 views Asked by At

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?

2

There are 2 answers

4
xanatos On BEST 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();
}
0
lolo_house On

For PCL library, and tested for my:

public static IEnumerable<FieldInfo> DeclaredFields(Type type)
    {
        var fields = new List<FieldInfo>();

        while (type != null)
        {
            fields.AddRange(type.GetRuntimeFields());
            type = type.GetTypeInfo().BaseType;
        }

        return fields;
    }