C#中的反射和擴充方法的運用

來源:互聯網
上載者:User

標籤:length   this   抽取   異常   小項目   static   mod   對象   ace   

      前段時間做了一個練手的小項目,名叫Book_Bar,用來賣書的,採用的是三層架構,也就是Models,IDAL,DAL,BLL 和 Web , 在DAL層中各個類中有一個方法比較常用,那就是 RowToClass ,顧名思義,也就是將 DataTable 中的資料封裝到 Models 中。結果導致在DAL各個類中寫了很多類似的方法,後來就直接把它抽取出來做成了 DataTable和 DataRow的擴充方法,

下面是代碼:

using System;using System.Collections.Generic;using System.Data;using System.Reflection;namespace DAL{    /// <summary>    /// 用於給 DataTable和 DataRow擴充方法    /// </summary>    public static class TableExtensionMethod    {        /// <summary>        /// 功能:        ///     給DataTable擴充了一個方法,能夠將DataTable中的行轉變為對應的class對象,並封裝到List集合中;        /// </summary>        /// <typeparam name="T">需要轉變成為的class類型</typeparam>        /// <param name="table">傳入的DataTable對象</param>        /// <returns>返回一個封裝了對應class的List集合</returns>        public static List<T> TableToClass<T>(this DataTable table)        {            Type type = typeof(T);            PropertyInfo[] propArr = type.GetProperties();//擷取所有屬性            List<T> list = new List<T>();            DataRowCollection rows = table.Rows;            int len = rows[0].ItemArray.Length;//擷取第一行的列數,即class的屬性個數            for (int i = 0; i < rows.Count; i++)            {                T t = (T)Activator.CreateInstance(type);                for (int j = 0; j < len; j++)//這裡之所以不使用propArr.Length,是因為有些Models的屬性在資料表中不存在對應的列                {                    propArr[j].SetValue(t, rows[i][j]);                }                list.Add(t);                t = default(T);            }            return list;        }        /// <summary>        /// 功能:        ///     DataRow的擴充方法;        ///     能夠將DataRow對象封裝到泛型對象中        /// </summary>        /// <typeparam name="T">需要轉換成為的class類型</typeparam>        /// <param name="row">被轉換的行</param>        /// <returns>封裝了行資料的class對象</returns>        public static T RowToClass<T>(this DataRow row)        {            //Type type = Assembly.Load(classFullName).GetType();            Type type = typeof(T);            T t = (T)Activator.CreateInstance(type);            PropertyInfo[] propArr = type.GetProperties();            int len = row.ItemArray.Length;            for (int i = 0; i < len; i++)            {                propArr[i].SetValue(t, row[i]);            }            return t;        }        /// <summary>        /// 功能:        ///     DataRowCollection的擴充方法;        ///     能夠將DataRowCollection對象封裝到泛型List集合中        /// </summary>        /// <typeparam name="T"></typeparam>        /// <param name="rows"></param>        /// <returns></returns>        public static List<T> RowToClass<T>(this DataRow row, DataRow[] rowArr)        {            Type type = typeof(T);            PropertyInfo[] propArr = type.GetProperties();            int len = rowArr[0].ItemArray.Length;//擷取資料表第一行的列數,即屬性個數            List<T> list = new List<T>();            for (int i = 0; i < rowArr.Length; i++)            {                T t = (T)Activator.CreateInstance(type);                for (int j = 0; j < len; j++)                {                    propArr[j].SetValue(t, rowArr[i][j]);                }                list.Add(t);                t = default(T);            }            return list;        }    }}

上面用到了泛型,反射,擴充方法。

之前在使用這行代碼時出了點小問題:

propArr[i].SetValue(t, row[i]);

      報了一個類型轉換異常,斷點調試之後發現是因為 Models 中的屬性的排列和資料表的列的順序不一樣導致的,參照資料表中欄位的順序修改過來就好,還有一點就是在迴圈對屬性進行賦值時,我選用的是資料表中列的個數,而不是屬性的個數,(也就是代碼中黃色部分)。

C#中的反射和擴充方法的運用

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.