通過反射填充泛型集合List的靜態方法
如何通過反射,從DataReader將數據填充到數據實體泛型集合的靜態方法.
//Kchen.Core.BaseBusinessObject爲通用數據實體類,此處僅爲限定T所繼承的類型
public static IList<T> FillDataListGeneric<T>(System.Data.IDataReader reader) where T : Kchen.Core.BaseBusinessObject //,new()
{
//實例化一個List<>泛型集合
IList<T> DataList = new List<T>();
while (reader.Read())
{
//由於是是未知的類型,所以必須通過Activator.CreateInstance<T>()方法來依據T的類型動態創建數據實體對象
T RowInstance = Activator.CreateInstance<T>();
//T加了NEW()後就可以直接實例化了 T RowInstance = new 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,快速的將數據填充到數據實體泛型集合中.
本文來自CSDN博客,轉載請標明出處:http://blog.csdn.net/wfz131/archive/2008/11/21/3345071.aspx