If it is C , we can calculate the location of the members within the object, then offset the pointer to access all non-public members of the type. However, .NET object is completely affected by GC, and the address is not available at all, and it is not possible to call the method.
Of course ... this is a very uncomfortable technique, accessing non-public members are likely to destroy the status, causing unpredictable consequences. But in any case, you can easily do this with the reflex mechanism of .NET.
For example, such a class:
Class myclass {private string princefield = "private field"; protected string protectedfield = "protected field";
Private string _protectedproperty = "protected protected"; protected string protectedproperty {get {return _ProtectedProperty;} set {_protectedproperty = value;}}
Private string _PrivateProperty = "properties"; private string privateproperty {get {return _privateproperty;} set {_privateproperty = value;}}
Protected void protected () {console.writeline ("protected method invoked";
Private void privateMethod () {console.writeline ("private method invoked");}}
In addition to the default constructor, no members are open, but I still want to get and set the value of Field and Property, and call that two methods. the way is:
Myclass mc = new myclass ();
TYPE T = TypeOf (MyClass);
Bindingflags bf = bindingflags.instance | bindingflags.nonpublic;
// fields
FieldInfo Fi_Protected = T.Getfield ("protectedfield", bf);
FieldInfo Fi_Private = T.Getfield ("Privatefield", BF);
Console.writeline (FI_PROTECTED.GETVALUE (MC));
Console.writeLine (FI_PRIVATE.GETVALUE (MC));
FI_PRIVATE.SETVALUE (MC, "New Private Field");
Console.writeLine (FI_PRIVATE.GETVALUE (MC));
Console.writeLine ();
// Properties
PropertyInfo Pi_Protected = T. GetProperty ("ProtectedProperty", BF);
PropertyInfo Pi_private = T.GetProperty ("PrivateProperty", BF);
Console.writeline (Pi_Protected.getValue (MC, NULL);
Console.writeline (Pi_Private.getValue (MC, NULL)); PI_Private.SetValue (MC, "New Private Property", NULL);
Console.writeline (pi_private.getValue (mc, null);
Console.writeLine ();
//Methods
MethodInfo Mi_Protected = T. GetMethod ("ProtectedMethod", BF);
MethodInfo MI_PRIVATE = T. GetMethod ("PrivateMethod", BF);
Mi_Protected; MC, NULL
MI_PRIVATE.INVOKE (MC, NULL);
Console.readline ();
Output:
Protected Field
Private field
New Private field
Protected Property
Private Property
New Private Property
Protected method invoked
Private method invoked
In addition to Field, Property, Method, there is a member of the object? Yes, events, the answer is EventInfo :-)