Blackboard
Perspectives and thoughts from Zhenhua Yao
Bypass access restrictions in managed code
08 May 2012
For some reason I need to access a private field in a class in the system library. .NET provides a way to do it.
I think it will be cool to share it although it is not a good coding practice that we will be using it on a regular
basis.
Hypothetically suppose we want to construct an instance of System.ConfigNode. This class is an internal class in
mscorlib, and the constructor is internal too. So we cannot just use it as usual.
Fortunately we have System.Reflection. Firstly we load the assembly and find the type:
The we can construct an instance:
or
Now we can change a private field:
or call a private method:
BTW, the format for the code is horrible. I need to find a better way to handle this.