I want to access protected member in a class. Is there a simple way?
There are two ways:
#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 love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With