C#中通過反射獲取類中非公有成員


       

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()用來獲取屬性。

 

 
示例:
如圖,我要獲取_row和Row的值。

\
    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進行反射操作               }         }
 
 
深入:
如圖,兩者都有相似的參數類型,可以只輸入要搜索的Name參數,也可以額外加入負責搜索執行方式的參數BindingAttr。
\
      BindingAttr的參數大體如下(來自MSDN):
      指定 BindingFlags.Public 可在搜索中包含公共字段。
      指定 BindingFlags.NonPublic 可在搜索中包含非公共字段(即私有字段、內部字段和受保護的字段)。
      指定 BindingFlags.FlattenHierarchy 以便沿層次結構向上包括public 和protected 靜態成員;不包括繼承類中的private 靜態成員。
      BindingFlags.IgnoreCase,表示忽略name 的大小寫。

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

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM