首页 > 其他 > 详细

反射类属性生成DataTable

时间:2016-05-05 17:31:33      阅读:121      评论:0      收藏:0      [点我收藏+]
    public class People        //类名 
    {
        private static string name;    //字段 

        private string sex;//字段 

        public string Sex     //属性 
        {
            get { return sex; }
            set { sex = value; }
        }

        public static string Name    //属性 
        {
            get { return People.name; }
            set { People.name = value; }
        }
    }

 

    class Program
    {
        static void Main(string[] args)
        {
            DataTable dt = new DataTable("dt");
            GetTableByClass<People>(ref dt);
            Console.ReadKey();
        }

        /// <summary>
        /// 反射类属性添加到DataTable
        /// </summary>
        /// <typeparam name="T">泛型类</typeparam>
        public static void GetTableByClass<T>(ref DataTable dt)
        {
            Type t = typeof(T);
            MemberInfo[] members = t.GetMembers();
            List<string> ls = new List<string>();
            foreach (MemberInfo member in members)
            {
                if (member.MemberType == MemberTypes.Property)
                {
                    ls.Add(member.Name);
                }
            }
            AddArryFieldToTable(ref dt, ls);
        }
        /// <summary>
        /// 添加数组字段到DataTable
        /// </summary>
        public static void AddArryFieldToTable(ref DataTable dt, List<string> fieldNames)
        {
            foreach (string fieldName in fieldNames)
            {
                AddFieldToTable(ref dt, fieldName);
            }
        }
        /// <summary>
        /// 添加字段到DataTable
        /// </summary>
        public static void AddFieldToTable(ref DataTable dt, string fieldName)
        {
            DataColumn c = new DataColumn();
            c.DataType = System.Type.GetType("System.String");
            c.ColumnName = fieldName;
            dt.Columns.Add(c);
        }
    }

 

反射类属性生成DataTable

原文:http://www.cnblogs.com/xushining/p/5462557.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!