If it is C ++, we can calculate the position of the members in the object, and then offset the pointer to access all non-public members of the type. However, the. NET object is completely managed by GC, and the address cannot be obtained at all, and the method cannot be called through the pointer.
Of course... This isNot recommendedThe access to non-public members is likely to damage the object status and cause unpredictable consequences. However, in any case, the reflection mechanism of. NET can be used to easily achieve this.
For example, a class:
Class MyClass
{
Private string PrivateField = "Private Field ";
Protected string ProtectedField = "Protected Field ";
Private string _ ProtectedProperty = "Protected Property ";
Protected string ProtectedProperty
{
Get {return _ ProtectedProperty ;}
Set {_ ProtectedProperty = value ;}
}
Private string _ PrivateProperty = "Private Property ";
Private string PrivateProperty
{
Get {return _ PrivateProperty ;}
Set {_ PrivateProperty = value ;}
}
Protected void ProtectedMethod ()
{
Console. WriteLine ("Protected Method Invoked ");
}
Private void PrivateMethod ()
{
Console. WriteLine ("Private Method Invoked ");
}
}
No member except the default constructor is public, but I still want to get and set the value of Field and Property, and call the two methods. The method is:
MyClass mc = new MyClass (); Type t = typeof (MyClass); BindingFlags bf = BindingFlags. instance | BindingFlags. nonPublic; // FieldsFieldInfo 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 (); // PropertiesPropertyInfo 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 (); // MethodsMethodInfo mi_protected = t. getMethod ("ProtectedMethod", bf); MethodInfo mi_private = t. getMethod ("PrivateMethod", bf); mi_protected.Invoke (mc, null); mi_private.Invoke (mc, null); Console. readLine ();
Output:
Protected FieldPrivate FieldNew Private FieldProtected PropertyPrivate PropertyNew Private PropertyProtected Method InvokedPrivate Method Invoked