Is there any way to get value of private static field from known class using reflection?
A variable declared private static could easily be accessed, but only from the inside of the class in which it is defined and declared. It is because the variable is declared private, and private variables are not accessible outside the class. Within the class, they can be accessed using ClassName. Variable_name .
Just like an instance variables can be private or public, static variables can also be private or public.
It can be accessed by any member function of the class. Normally, it is accessed with the class scope operator. If it is private, use a static member function to read or write it. A static member function: • Is like an ordinary non-member function, but its scope is the class.
So: field. set(null, p_fieldValue); This will let you set the static field.
Yes.
Type type = typeof(TheClass); FieldInfo info = type.GetField(name, BindingFlags.NonPublic | BindingFlags.Static); object value = info.GetValue(null);
This is for a field. For a property, change type.GetField
to type.GetProperty
. You can also access private methods in a similar fashion.
I suppose someone should ask whether this is a good idea or not? It creates a dependency on the private implementation of this static class. Private implementation is subject to change without any notice given to people using Reflection to access the private implementation.
If the two classes are meant to work together, consider making the field internal and adding the assembly of the cooperating class in an [assembly:InternalsVisibleTo] attribute.
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