Use reflection to view private variables in an object

Source: Internet
Author: User
In Program During the design, we may write some underlying libraries, including some core classes, which usually encapsulate some private methods and private variables. When the program is not completed, we may need to debug it to check whether the defined class has any errors.
Of course, this library may also come from other developers.
We may check the private variables in the class during debugging.

My personal habit is to write a DLL that I think is more important to test it to verify its correctness.

Debugging is different from testing.
Debugging means you may not know the final running result of the program, and testing means you confirm the input, you can predict the output, so you can verify the final result.

There are a lot of reflection materials, so I will not specifically talk about how to view all the methods in a class. All the members have finished.
Suppose I already know the name of a private member and now there is an object of this type. What should I do if I want to know the value of a private member?
Let's take a look.CodeIt is easy to know how to view the private members of an object through reflection.

Type mytype = OBJ. GetType ();
Fieldinfo = Mytype. getfield ( " _ Usercouldexecutedt " , Bindingflags. nonpublic | Bindingflags. Instance | Bindingflags. Public );
If (Fieldinfo ! = Null )
{
String SS=(String) Fieldinfo. getvalue (OBJ );
Console. writeline (SS );
}

It's easy.

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.