Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to read out protected member

Tags:

c#

.net

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

like image 950
user496949 Avatar asked Dec 28 '22 04:12

user496949


2 Answers

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.

like image 54
Dean Harding Avatar answered Jan 10 '23 15:01

Dean Harding


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);
    }
like image 27
Phil Wright Avatar answered Jan 10 '23 15:01

Phil Wright