日期:2014-05-17  浏览次数:20453 次

利用反射,DataReader填充泛型集合List<T>
网上找的代码,稍微改了一下,请问这样做是否会有效率问题,或者,还有没有其它更好、更方便的方法填充List<T>?(ORM除外)

        public static List<T> ToList<T>(IDataReader reader)
        {

            //实例化一个List<>泛型集合
            List<T> DataList = new List<T>();
            while (reader.Read())
            {
                T RowInstance = Activator.CreateInstance<T>();//动态创建数据实体对象

                //通过反射取得对象所有的Property
                foreach (PropertyInfo Property in typeof(T).GetProperties())
                {
                    foreach (BindingFieldAttribute FieldAttr in Property.GetCustomAttributes(typeof(BindingFieldAttribute), true))
                    {
                        try
                        {
                            //取得当前数据库字段的顺序
                            int Ordinal = reader.GetOrdinal(FieldAttr.FieldName);
                            if (reader.GetValue(Ordinal) != DBNull.Value)
                            {
                                //将DataReader读取出来的数据填充到对象实体的属性里