C#扩展方法 DataTable.ToEntitys

类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>();

原文地址:https://www.cnblogs.com/linmilove/p/7892608.html