Csharp/C#教程: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#程序设计有所帮助。

上述就是C#学习教程:C#实现利用泛型将DataSet转为Model的方法分享的全部内容,如果对大家有所用处且需要了解更多关于C#学习教程,希望大家多多关注—计算机技术网(www.ctvol.com)! 您可能感兴趣的文章:C#泛型参数转换C#中数组Array,ArrayList,泛型List详细对比C#中Dictionary泛型集合7种常见的用法深入解析C#中的泛型类与泛型接口关于C#泛型列表List<T>的基本用法

本文来自网络收集,不代表计算机技术网立场,如涉及侵权请联系管理员删除。

ctvol管理联系方式QQ:251552304

本文章地址:https://www.ctvol.com/cdevelopment/907312.html

(0)
上一篇 2021年10月24日
下一篇 2021年10月24日

精彩推荐