When we learn C # The first set of keywords to contact may be Private, public, protect.
Private is defined as: methods and variables defined with this keyword can only be used inside an object.
But is this absolute? Is there a way to use private defined methods or variables in the caller's space?
Let's define one of the following classes:
- Public class Testobj
- {
- Public string Publicvalue { get; set; }
- Private string _privatevalue;
- public Testobj ()
- {
- _privatevalue = "private";
- Publicvalue = "public";
- }
- Public testobj (string value)
- {
- _privatevalue = "private_" + value;
- Publicvalue = "public_" + value;
- }
- Private string returnprivatevalue ()
- {
- return _privatevalue;
- }
- }
So can we access _priavatevalue in this simple program?
- Static void Main (string[] args)
- {
- Testobj to = new testobj ("test");
- Console.WriteLine ("obj public parameter:{0}" to. Publicvalue);
- Console.WriteLine ("obj public parameter:{0}", to. Returnprivatevalue ());
- Console.read ();
- }
We get a compile error when we try to compile this simple program.
' PrivateCallByReflection.testObj.returnPrivateValue () ' is inaccessible due to its protection level
So private is really safe, can only be accessed internally?
A little trick can get the results we want.
- Static void Main (string[] args)
- {
- Testobj to = new testobj ("test");
- Console.WriteLine ("obj public parameter:{0}" to. Publicvalue);
- //console.writeline ("obj Public parameter:{0}", To.returnprivatevalue ());
- MethodInfo Privatemethod = typeof(testobj). GetMethod ("returnprivatevalue", BindingFlags.Instance | BindingFlags.NonPublic);
- Console.WriteLine ("obj Private method ' Returnprivatevalue ' return: {0}", Privatemethod.invoke (to, new Object[] {});
- Console.read ();
- }
Please note the underlined code.
Reflection helps us to access a private method.
No lower limit of reflection, really there is nothing to do .....
Private methods are closed? Use reflection to invoke a private method of an object.