Cool Blue
Cool Blue

Reputation: 6476

Can't access private field with Type.GetMember in wpf

The following code fails to find private fields, for example if host is Application.Current and member is "_ownDispatcherStarted", it returns an empty array, but if if I look for a private property, for example member is "ParkingHwnd", it returns an array of length 1; it finds it ok. Why is that?

        var hostType = host.GetType();
        var members = host.GetType()
            .GetMember(member, Public | NonPublic | Instance);

Upvotes: 1

Views: 165

Answers (1)

Jonathan Gilbert
Jonathan Gilbert

Reputation: 3840

I just did some experimentation. According to the documentation, you need to specify BindingFlags.DeclaredOnly in order to exclude inherited members, but in my tests, I found that I could not get inherited members to appear in returned values from GetMember, GetFields or GetField.

With a default WPF application, Application.Current is not an instance of Application directly, but of the subclass of Application defined in App.xaml. I found that if I used host.GetType().BaseType, then fields such as _ownDispatcherStarted were discoverable.

So, in order to generically find fields declared by the Application base class, you may need to walk up the inheritance tree, repeatedly following BaseType until you either find the member you're looking for or hit the root.

This isn't the result I expected, but hopefully it'll get you going. :-)

Upvotes: 3

Related Questions