Miles
Miles

Reputation: 526

Can't get field through reflection

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

Upvotes: 2

Views: 1528

Answers (4)

dcastro
dcastro

Reputation: 68640

  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

Upvotes: 3

Mzf
Mzf

Reputation: 5260

Try using GetNestedTypes

Type[] myTypeArray = myType.GetNestedTypes(BindingFlags.NonPublic|BindingFlags.Instance);

Upvotes: 1

Dennis_E
Dennis_E

Reputation: 8894

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

Upvotes: 0

James
James

Reputation: 82096

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)

Upvotes: 3

Related Questions