這篇文章主要介紹了C#實現利用泛型將DataSet轉為Model的方法,實例分析了C#泛型的相關使用技巧,具有一定參考借鑒價值,需要的朋友可以參考下
本文實例講述了C#實現利用泛型將DataSet轉為Model的方法。分享給大家供大家參考。具體如下:
因為網站需要用C#開發,習慣了java的泛型,所以看了一下C#下,也可以這樣做,隨便寫了一個。
- public static List<T> PutAllVal<T>(T entity, DataSet ds) where T : new() {
- List<T> lists = new List<T>();
- if (ds.Tables[0].Rows.Count > 0) {
- foreach (DataRow row in ds.Tables[0].Rows) {
- lists.Add(PutVal(new T(),row));
- }
- }
- return lists;
- }
- public static T PutVal<T>(T entity, DataRow row) where T : new() {
- //初始化 如果為null
- if (entity == null){
- entity = new T();
- }
- //得到類型
- Type type = typeof(T);
- //取得屬性集合
- PropertyInfo[] pi = type.GetProperties();
- foreach (PropertyInfo item in pi){
- //給屬性賦值
- if (row[item.Name] != null && row[item.Name] != DBNull.Value) {
- if (item.PropertyType == typeof(System.Nullable<System.DateTime>)) {
- item.SetValue(entity, Convert.ToDateTime(row[item.Name].ToString()), null);
- } else {
- item.SetValue(entity, Convert.ChangeType(row[item.Name], item.PropertyType), null);
- }
- }
- }
- return entity;
- }
希望本文所述對大家的C#程序設計有所幫助。
|
新聞熱點
疑難解答