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();
}
}
如果需要獲取NGlbFieldX中的mpr_org成員 使用如下語句
string fd = NGlbGlobeXComm.GetPrivateField<string>(field, "mpr_org");
即可得到。
參考:
一般而言,非公共成員是受保護的,不能被外部訪問的,這些都是基於安全性考慮。可是有時,我們很想取到非公共成員的某個對象。那我們就得用到兩個方法:
GetType().GetField();
GetType().GetProperty();
GetField()用來獲取字段,GetProperty()用來獲取屬性。

protected void GV_Event_RowCommand(object sender, GridViewCommandEventArgs e) { if (e.CommandName == "gvwEventLinkButton") { //_row 前面藍色小圖標,是變量(字段), 他是私有成員 //Row 前面白色小圖標,是屬性 ,他是保護乘員(白色圖標上有個H的區域) //是字段還是屬性,根據命名也能看出來 //根據調試時查看,Row類型是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; //如果RowIndex仍然是非公成員,可以同理對row進行反射操作 } }

BindingFlags.DeclaredOnly,表示僅搜索在Type 上聲明的字段,而不搜索簡單繼承的字段。