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 StringName;
- Public StringName
- {
- Get
- {
- ReturnName;
- }
- 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 StaticT GetPrivateField <T> (This ObjectInstance,StringFieldname)
- {
- 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 StaticT GetPrivateProperty <T> (This ObjectInstance,StringPropertyname)
- {
- 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 VoidSetPrivateField (ThisObjectinstance, 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 VoidSetPrivateProperty (ThisObjectinstance, stringpropertyname, objectvalue)
- {
- BindingFlagsflag = BindingFlags. Instance | BindingFlags. NonPublic;
- Typetype = instance. GetType ();
- PropertyInfofield = type. GetProperty (propertyname, flag );
- Field. SetValue (instance, value,Null