2

Here is my class:

public static class Root
{
    private static readonly NestedOne nestedOne;

    static Root()
    {
        nestedOne = new NestedOne();
    }

    class NestedOne
    {
        private string FindMe = "blabla";
    }
}

I need get that field that called 'FindMe' through the Root. I successfully get the instance of NestedOne:

var nestedOne = typeof(Root).GetField("nestedOne", System.Reflection.BindingFlags.Static | System.Reflection.BindingFlags.NonPublic);

But can't get further:

var fields = nestedOne.GetType().GetFields(BindingFlags.NonPublic);  // there is empty

Please help me

Sergey Berezovskiy
  • 232,247
  • 41
  • 429
  • 459
Miles
  • 488
  • 5
  • 19
  • This is also helpful: [link](http://stackoverflow.com/questions/95910/find-a-private-field-with-reflection) – Daniel Jun 23 '14 at 10:43

4 Answers4

3
  1. nestedOne is an instance of FieldInfo.
  2. Calling nestedOne.GetType() will give you an instance of Type that represents the FieldInfo type.
  3. Since Type has no fields, you get an empty collection.

What you want to do is use the FieldType property instead of calling .GetType()

nestedOne.FieldType.GetFields(...)

You also need to specify the BindingFlags.Instance flag for instance fields.

Demo: https://dotnetfiddle.net/kZxvMp

dcastro
  • 66,540
  • 21
  • 145
  • 155
3

The field you are looking for is an instance field, you need to include that category in your search by specifying the BindingFlags.Instance flag

GetFields(BindingFlags.NonPublic | BindingFlags.Instance)
James
  • 80,725
  • 18
  • 167
  • 237
1

Try using GetNestedTypes

Type[] myTypeArray = myType.GetNestedTypes(BindingFlags.NonPublic|BindingFlags.Instance);
Mzf
  • 5,210
  • 2
  • 24
  • 37
0

According to the MSDN documentation you must specify BindingFlags.Instance http://msdn.microsoft.com/en-us/library/6ztex2dc%28v=vs.110%29.aspx

Dennis_E
  • 8,751
  • 23
  • 29