Is the private method closed? Use reflection to call the private method of an object ., Private closed

Source: Internet
Author: User

Is the private method closed? Use reflection to call the private method of an object ., Private closed

When we learn C #, the first set of keywords that we encounter may be Private, Public, and protect.

The definition of Private is: the methods and variables defined with this keyword can only be used inside the object.

But is this absolute? Is there a way to use Private-defined methods or variables in the caller's space?

Let's define the following class:

Can we access _ priavateValue in this simple program?

When we try to compile this simple program, we will get a compilation error.

'Privatecallbyreflection. testObj. returnPrivateValue () 'is inaccessible due to its protection level

So private is actually safe and can only be accessed internally?

A small trick can get the desired result.

Pay attention to the underlined code.

Reflection helps us access a Private method.

There is no lower limit of reflection. There is really nothing to do with it .....

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.