C#实现利用泛型将DataSet转为Model的方法
本文实例讲述了C#实现利用泛型将DataSet转为Model的方法。分享给大家供大家参考。具体如下:
因为网站需要用C#开发,习惯了java的泛型,所以看了一下C#下,也可以这样做,随便写了一个。
publicstaticList<T>PutAllVal<T>(Tentity,DataSetds)whereT:new(){ List<T>lists=newList<T>(); if(ds.Tables[0].Rows.Count>0){ foreach(DataRowrowinds.Tables[0].Rows){ lists.Add(PutVal(newT(),row)); } } returnlists; } publicstaticTPutVal<T>(Tentity,DataRowrow)whereT:new(){ //初始化如果为null if(entity==null){ entity=newT(); } //得到类型 Typetype=typeof(T); //取得属性集合 PropertyInfo[]pi=type.GetProperties(); foreach(PropertyInfoiteminpi){ //给属性赋值 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); } } } returnentity; }
希望本文所述对大家的C#程序设计有所帮助。