简体   繁体   中英

How to read out protected member

I want to access protected member in a class. Is there a simple way?

There are two ways:

  1. Create a sub-class of the class whose protected members you want to access.
  2. Use reflection.

#1 only works if you control who creates the instances of the class. If an already-constructed instance is being handed to you, then #2 is the only viable solution.

Personally, I'd make sure I've exhausted all other possible mechanisms of implementing your feature before resorting to reflection, though.

I have sometimes needed to do exactly this. When using WinForms there are values inside the system classes that you would like to access but cannot because they are private. To get around this I use reflection to get access to them. For example...

    // Example of a class with internal private field
    public class ExampleClass
    {
        private int example;
    }

    private static FieldInfo _fiExample;

    private int GrabExampleValue(ExampleClass instance)
    {
        // Only need to cache reflection info the first time needed               
        if (_fiExample == null)
        {
            // Cache field info about the internal 'example' private field
            _fiExample = typeof(ExampleClass).GetField("example", BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.GetField);
        }

        // Grab the internal property
        return (int)_fiExample.GetValue(instance);
    }

If you can derive from the class that has that protected member than you can access it.
As for using reflection, this might help .

Have you chosen the right accessor for your member?

  1. protected (C# Reference) ;
  2. public (C# Reference) ;
  3. private (C# Reference) ;
  4. internal (C# Reference) .
  5. You may also combine internal with protected .

By all means, the protected accessor specifies that a member shall be accessed only within a derived class. So, if your objective is to access it outside of a derived class, perhaps should you rather consider using the public or internal accessor!?

Besides, that is doable throught Reflection (C# and Visual Basic) .

On the other hand, if you really want to expose the protected members of a class, I would try using public members and returning a reference to the protected through it.

But please, ask yourself whether your design is good before exposing protected members. It looks to me like a design smell.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM