zoukankan      html  css  js  c++  java
  • ASP.NET:通过反射填充泛型集合List的静态方法

    如何通过反射,从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,快速的将数据填充到数据实体泛型集合中.
  • 相关阅读:
    在EasyDarwin进行实时视频转发的两种模式
    Windows服务中读取配置文件的方法
    reactor设计模式
    用Darwin实现流媒体转发程序(附源码)
    Windows服务中读取配置文件的方法
    c# 参数 this
    基于DSS的先侦听后推送式流媒体转发
    用live555做本地视频采集转发,附源码
    Darwin在转发流过程中对推送端断开的处理问题
    基于live555的流媒体代理转发服务器
  • 原文地址:https://www.cnblogs.com/HondaHsu/p/734935.html
Copyright © 2011-2022 走看看