ASP.NET:通過反射填充泛型集合List的靜態方法

來源:互聯網
上載者:User
如何通過反射,從DataReader將資料填充到資料實體泛型集合的靜態方法.

 

//Kchen.Core.BaseBusinessObject為通用資料實體類,此處僅為限定T所繼承的類型
        public static IList<T> FillDataListGeneric<T>(System.Data.IDataReader reader) where T : Kchen.Core.BaseBusinessObject
        {
            //執行個體化一個List<>泛型集合
            IList<T> DataList = new List<T>();
            while (reader.Read())
            {
                //由於是是未知的類型,所以必須通過Activator.CreateInstance<T>()方法來依據T的類型動態建立資料實體物件
                T RowInstance = Activator.CreateInstance<T>();
                //通過反射取得對象所有的Property
                foreach (PropertyInfo Property in typeof(T).GetProperties())
                {
                    //BindingFieldAttribute為自訂的Attribute,用於與資料庫欄位進行綁定
                    foreach (BindingFieldAttribute FieldAttr in Property.GetCustomAttributes(typeof(BindingFieldAttribute), true))
                    {
                        try
                        {
                            //取得當前資料庫欄位的順序
                            int Ordinal = reader.GetOrdinal(FieldAttr.FieldName);
                            if (reader.GetValue(Ordinal) != DBNull.Value)
                            {
                                //將DataReader讀取出來的資料填充到對象實體的屬性裡
                                Property.SetValue(RowInstance, Convert.ChangeType(reader.GetValue(Ordinal), Property.PropertyType), null);
                            }
                        }
                        catch
                        {
                            break;
                        }
                    }
                }
                //將資料實體物件add到泛型集合中
                DataList.Add(RowInstance);
            }
            return DataList;
        }
調用的時候使用如下代碼

            //虛擬碼 OleDbDataReader _ds = 建立一個OleDbDataReader
            IList<Product> _result = Kchen.Utilities.FillDataListGeneric<Product>(_ds);

此靜態方法通過一個實體類型和DateReader,快速的將資料填充到資料實體泛型集合中.

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

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.