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:
Output: