• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

C#扩展方法DataTable.ToEntitys

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

类A需要添加功能,我们想到的就是在类A中添加公共方法,这个显而易见肯定可以,但是由于某种原因,你不能修改类A本身的代码,但是确实又需要增加功能到类A中去,怎么办? 这个时候扩展方法(Extension Methods)就会帮助你完成上述功能了。现在举例如下为DataTable添加一个转ToEntities方法:

扩展方法实现:

using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;

namespace CNN
{
    //必需静态类
    public static class ExtendClass
    {
        //必需静态方法,并且使用this关键字修饰
        public static IEnumerable<T> ToEntitys<T>(this DataTable @this) where T : new()
        {
            Type type = typeof(T);
            PropertyInfo[] properties = type.GetProperties(BindingFlags.Instance | BindingFlags.Public);
            FieldInfo[] fields = type.GetFields(BindingFlags.Instance | BindingFlags.Public);
            List<T> list = new List<T>();
            foreach (DataRow dr in @this.Rows)
            {
                T entity = (default(T) == null) ? Activator.CreateInstance<T>() : default(T);
                PropertyInfo[] array = properties;
                for (int i = 0; i < array.Length; i++)
                {
                    PropertyInfo property = array[i];
                    if (@this.Columns.Contains(property.Name))
                    {
                        Type valueType = property.PropertyType;
                        property.SetValue(entity, dr[property.Name].To(valueType), null);
                    }
                }
                FieldInfo[] array2 = fields;
                for (int j = 0; j < array2.Length; j++)
                {
                    FieldInfo field = array2[j];
                    if (@this.Columns.Contains(field.Name))
                    {
                        Type valueType2 = field.FieldType;
                        field.SetValue(entity, dr[field.Name].To(valueType2));
                    }
                }
                list.Add(entity);
            }
            return list;
        }
    }
}

 

扩展方法使用:

DataTable dt = GetTable();
var list = dt.ToEntitys<MyEntitie>();


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap