Access private members in C #

Source: Internet
Author: User

First, it is not a good practice to access a private member of a class. We all know that Private Members cannot be accessed externally. A class contains many private members, such as private fields, private attributes, and private methods. For private member access, you can use the following method to solve the problem.

private string name;public string Name{    get    {        return name;    }    set    {        name = value;    }}

 

However, sometimes the source code is provided only to your dll. Or you can maintain others' code, but the source code is lost. In this case, you may want to know the value of the Private member, or even directly call the private method in the class. What should we do? It is not very difficult to access private members in. net. This article provides several simple methods for you to do so.

To make the code more elegant, use the extension method.

1. Obtain the private field value:

public static T GetPrivateField<T>(this object instance, string fieldname){    BindingFlags flag = BindingFlags.Instance | BindingFlags.NonPublic;    Type type = instance.GetType();    FieldInfo field = type.GetField(fieldname, flag);    return (T)field.GetValue(instance);}

2. Obtain the private property value:

public static T GetPrivateProperty<T>(this object instance, string propertyname){    BindingFlags flag = BindingFlags.Instance | BindingFlags.NonPublic;    Type type = instance.GetType();    PropertyInfo field = type.GetProperty(propertyname, flag);    return (T)field.GetValue(instance, null);}

3. Set the private member value:

Public static void SetPrivateField (this objectinstance, stringfieldname, objectvalue)
{
BindingFlagsflag = BindingFlags. Instance | BindingFlags. NonPublic;
Typetype = instance. GetType ();
FieldInfofield = type. GetField (fieldname, flag );
Field. SetValue (instance, value );
}
4. Set the private attribute value:
Public static void SetPrivateProperty (this objectinstance, stringpropertyname, objectvalue)
{
BindingFlagsflag = BindingFlags. Instance | BindingFlags. NonPublic;
Typetype = instance. GetType ();
PropertyInfofield = type. GetProperty (propertyname, flag );
Field. SetValue (instance, value, null );
}
5. Call Private methods:

public static T CallPrivateMethod<T>(this object instance, string name, params object[] param){    BindingFlags flag = BindingFlags.Instance | BindingFlags.NonPublic;    Type type = instance.GetType();    MethodInfo method = type.GetMethod(name, flag);    return (T)method.Invoke(instance, param);}

Test:

Next we will use a test class for testing. Create a class library project and test the Class Code as follows:

public class TestClass{    public TestClass()    {        privatefield1 = 1;        privatefield2 = 99;        PrivateFieldA = "Lo";        PrivateFieldB = "ve";    }    private int privatefield1;    private int privatefield2;      private string PrivateFieldA    {        get;        set;    }    private string PrivateFieldB    {        get;        set;    }    private int Add()    {        return privatefield1 + privatefield2;    }    private string Join()    {        return PrivateFieldA + PrivateFieldB;    }}

Introduce the dll of the above class library into the console project. Use the following code to use private members of this class:

TestClass obj = new TestClass (); System. console. writeLine ("private field"); System. console. writeLine (obj. getPrivateField <int> ("privatefield1"); System. console. writeLine (obj. getPrivateField <int> ("privatefield2"); System. console. writeLine ("private property"); System. console. writeLine (obj. getPrivateProperty <string> ("PrivateFieldA"); System. console. writeLine (obj. getPrivateProperty <string> ("PrivateFieldB"); System. console. writeLine ("Private method"); System. console. writeLine (obj. callPrivateMethod <int> ("Add", null); System. console. writeLine (obj. callPrivateMethod <string> ("Join", null); System. console. writeLine ("modifying private attributes"); obj. setPrivateProperty (
 
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.