public class Nglbglobexcomm
{
public static T Getprivatefield<t> (object instance, string fieldname)
{
BindingFlags flag = BindingFlags.Instance | BindingFlags.NonPublic;
Type type = instance. GetType ();
FieldInfo field = type. GetField (fieldname, Flag);
T to = default (t);
Try
{
to = (T) field. GetValue (instance);
}catch (Exception e) {}
return to;
}
}
public class Nglbfieldx:nobjectsafety, INGLBFIELDX
{
private string mpr_org = null;
Public Nglbfieldx ()
{
mpr_org = new Nglbfield ();
}
}
If you need to get mpr_org members in NGLBFIELDX use the following statement
string fd = nglbglobexcomm.getprivatefield<string> (field, "mpr_org");
can be obtained.
Reference:
Generally, non-public members are protected and cannot be accessed externally, and these are based on security considerations. Sometimes, however, we would like to take an object from a non-public member. Then we need to use two methods:
GetType (). GetField ();
GetType (). GetProperty ();
GetField () is used to get the field, and GetProperty () is used to get the property.
Example:, I want to get the value of _row and row.
protected void Gv_event_rowcommand (object sender, Gridviewcommandeventargs e) {if (e.commandname = = "Gvweventlinkbutton") {//_row front blue small icon, is a variable (field), he is a private member//row front white small icon, is property, he is the protection of the occupant (the white icon has an area of h)//is a field or a property, according to the name can also be seen//based on debugging, the row type is GridViewRow GridViewRow row = null; System.Reflection.FieldInfo frow = E.gettype (). GetField ("_row", BindingFlags.Instance | BindingFlags.NonPublic); row = Frow.getvalue (e) as GridViewRow; int rowIndex = row. RowIndex; GridViewRow row2 = null; System.Reflection.PropertyInfo PRow = E.gettype (). GetProperty ("Row", BindingFlags.Instance | BindingFlags.NonPublic); Row2 = Prow.getvalue (e, null) as GridViewRow; int rowIndex2 = Row2. RowIndex; If rowindex is still a non-public member, you can do the same with row reflection}}
In-
depth:, both have similar parameter types, you can enter only the name parameter that you want to search, or you can add additional parameter bindingattr that are responsible for how the search executes. the parameters of the bindingattr are broadly as follows (from MSDN):Specifies that bindingflags.public can include public fields in the search. Specifies that bindingflags.nonpublic can include non-public fields (that is, private fields, internal fields, and protected fields) in the search. Specifies BindingFlags.FlattenHierarchy to include both public and protected static members along the hierarchy, excluding private static members in the inheriting class. Bindingflags.ignorecase, which indicates that the case of name is ignored.
BindingFlags.DeclaredOnly, which means that only fields declared on the type are searched, not simple inherited fields.
Get non-public members in a class by reflection in C #