. NET Program, access private or protect the skills of members,. net private

Source: Internet
Author: User

. NET Program, access private or protect the skills of members,. net private

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:

 

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.