1.

如果在网上搜一下.Net把List转换为DataTable,基本上都搜出类似如下一段代码:

DataTable dt = new DataTable();
 2 if (_list != null)
 3 {
      //通过反射获取list中的字段 
 4    System.Reflection.PropertyInfo[] p = _list[0].GetType().GetProperties();
 5    foreach (System.Reflection.PropertyInfo pi in p)
 6     {
 7       dt.Columns.Add(pi.Name, System.Type.GetType(pi.PropertyType.ToString()));
 8     }
 9    for (int i = 0; i < _list.Count; i++)
10    {
11        IList TempList = new ArrayList();
12         //将IList中的一条记录写入ArrayList
13        foreach (System.Reflection.PropertyInfo pi in p)
14        {
15          object oo = pi.GetValue(_list[i], null);
16          TempList.Add(oo);
17        }
18       object[] itm = new object[p.Length];
19      for (int j = 0; j < TempList.Count; j++)
20      {
21        itm.SetValue(TempList[j], j);
22      }
23      dt.LoadDataRow(itm, true);
       }
24 }

这段代码的思路是没有问题;但是实际运行会有问题;因为;

System.Reflection.PropertyInfo[] p = _list[0].GetType().GetProperties();

对于System.Int32类型,不会返回内容;p为空;不会添加列;

对于System.String类型,返回的值是2个;

2 做一个小程序来说明;

全部代码;

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Reflection;

namespace GetTypeGetPropertys
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

private void Form1_Load(object sender, EventArgs e)
        {
            PropertyInfo[] myPropertyInfo;
            // Get the properties of 'Type' class object.
            myPropertyInfo = Type.GetType("System.Type").GetProperties();
            for (int i = 0; i < myPropertyInfo.Length; i++)
            {
                //Console.WriteLine(myPropertyInfo[i].ToString());
                listBox1.Items.Add(myPropertyInfo[i].ToString());
            }

PropertyInfo[] props = Type.GetType("System.Int32").GetProperties();
            foreach (PropertyInfo prop in props)
            {
                listBox2.Items.Add(prop.ToString());
            }

PropertyInfo[] props2 = Type.GetType("System.String").GetProperties();            
            for (int i = 0; i < props2.Length; i++)
            {
                listBox3.Items.Add(props2[i].ToString());
            }

}
    }
}

界面和运行效果:

上述三个列表框返回的分别是System.Type、System.Int32、System.String调用GetProperties()返回的结果;微软对于GetProperties()方法的返回值有如下说明:

返回值

类型:System.Reflection.PropertyInfo[]
表示当前 Type 的所有公共属性的 PropertyInfo 对象数组。
- 或 -
如果当前 Type 没有公共属性,则为 PropertyInfo 类型的空数组。

实现

_Type.GetProperties()

3 所以现在要绑定一个List到DataGridView,代码只能如下:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Reflection;

namespace dataGridDemo
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

private void Form1_Load(object sender, EventArgs e)
        {
            List<int> li = new List<int>();
            //List<string> li = new List<string>();
            for (int i = 0; i < 32; i++)
            {
                //li.Add(i.ToString());
                li.Add(i);
            }
            DataTable tb = new DataTable();
            tb = ToDataTable(li);
            dataGridView1.DataSource = tb;
        }

private DataTable ToDataTable<T>(List<T> items)
        {
            var tb = new DataTable(typeof(T).Name);

//PropertyInfo[] props = typeof(T).GetProperties(BindingFlags.Public | BindingFlags.Instance);
            //PropertyInfo[] props = typeof(T).GetProperties();
            PropertyInfo[] props = items[0].GetType().GetProperties();
            //PropertyInfo[] props = Type.GetType("System.Int32").GetProperties();
            if (props.Count() == 0)
            {
                tb.Columns.Add(typeof(T).Name, typeof(T));
            }
            else
            {
                foreach (PropertyInfo prop in props)
                {
                    Type t = GetCoreType(prop.PropertyType);
                    tb.Columns.Add(prop.Name, t);
                }
            }

foreach (T item in items)
            {
                if (props.Count() == 0)
                {
                    var values = new object();

for (int i = 0; i < 32; i++)
                    {
                        //values = item.GetValue();
                        values=i;
                        tb.Rows.Add(values);
                    }
                    
                }
                else
                {
                    var values = new object[props.Length];

for (int i = 0; i < props.Length; i++)
                    {
                        values[i] = props[i].GetValue(item, null);
                    }

tb.Rows.Add(values);
                }
            }

return tb;
        }

/// <summary>
        /// Determine of specified type is nullable
        /// </summary>
        public static bool IsNullable(Type t)
        {
            return !t.IsValueType || (t.IsGenericType && t.GetGenericTypeDefinition() == typeof(Nullable<>));
        }

/// <summary>
        /// Return underlying type if type is Nullable otherwise return the type
        /// </summary>
        public static Type GetCoreType(Type t)
        {
            if (t != null && IsNullable(t))
            {
                if (!t.IsValueType)
                {
                    return t;
                }
                else
                {
                    return Nullable.GetUnderlyingType(t);
                }
            }
            else
            {
                return t;
            }
        }

}
}

运行结果;

关于反射GetType().GetProperties()的疑惑相关推荐

  1. C#基础系列:实现自己的ORM(反射以及Attribute在ORM中的应用)

    反射以及Attribute在ORM中的应用 一. 反射 什么是反射? 简单点吧,反射就是在运行时动态获取对象信息的方法,比如运行时知道对象有哪些属性,方法,委托等等等等. 反射有什么用呢? 反射不但让 ...

  2. 程序猿修仙之路--数据结构之你是否真的懂数组? c#socket TCP同步网络通信 用lambda表达式树替代反射 ASP.NET MVC如何做一个简单的非法登录拦截...

    程序猿修仙之路--数据结构之你是否真的懂数组? 数据结构 但凡IT江湖侠士,算法与数据结构为必修之课.早有前辈已经明确指出:程序=算法+数据结构  .要想在之后的江湖历练中通关,数据结构必不可少.数据 ...

  3. 一个简单的反射拷贝一份新的实体类

    有时候我们需要复制一个实体类,而又不希望两个使用同一个内存地址,我用了很简单的反射来实现这种功能:) /**//// <summary>         /// 设置实体对象的修改属性   ...

  4. C#强化系列文章五:动态代码的使用(反射和动态生成类)

    在软件开发尤其是框架和底层开发时,为了更灵活的控制代码,常常需要进行一些动态的操作.比如根据用户的输入等动态的调用类中的方法或者根据数据库表结构.用户要求动态的生成一些类,然后再动态的调用类中的方法. ...

  5. SqlHelper简单实现(通过Expression和反射)4.对象反射Helper类

    ObjectHelper的主要功能有: 1.通过反射获取Entity的实例的字段值和表名,跳过自增键并填入Dictionary<string,string>中. 1 namespace R ...

  6. [转]一个简单的反射拷贝一份新的实体类

    [IT168技术文档]   有时候我们需要复制一个实体类,而又不希望两个使用同一个内存地址,我用了很简单的反射来实现这种功能: /** <summary> /// 设置实体对象的修改属性 ...

  7. .NET架构小技巧(4)——反射,架构人员法宝II

    上一篇博文中,利用属性反射的特点,用两个方法完成了字符转实体,实体转字符的工作,但有些复杂的场景,上面方法就没那么好用了,就需要更复杂的方式来组装处理. 先来看一个接口文档,下面是接口的调用方式 lo ...

  8. [深入学习C#]利用反射给对象赋值

    转载自诗人江湖老,原文地址 C#中利用反射能够获取对象的属性信息,也可以利用反射给对象赋值. 我们如果想利用凡是给一个对象属性赋值可以通过PropertyInfo.SetValue()方式进行赋值,但 ...

  9. 反射之关于MethodInfo的使用

    1.MethodInfo类是在System.Reflection命名空间底下,既然是在Reflection空间底下.故名思议关于反射相关的操作,其中比较重要的方法是Invoke()方法,它 是加载相同 ...

最新文章

  1. java 获取泛型t的class_阿里巴巴都鼎力推荐的java基础之集合其他内容和泛型3
  2. 让神经网络给符号AI“打工”,MIT和IBM联合解决深度学习痛点,未来将用于自动驾驶...
  3. MAC下 IEDA发布tomcat项目的位置
  4. Linux 命令之 iostat 命令-监视系统输入输出设备和 cpu 的使用情况
  5. 图像检索在高德地图POI数据生产中的应用
  6. Django+xadmin 打造线上教育平台(二)-1(旧)
  7. Spring : BeanFactoryPostProcessor 子类 BeanDefinitionRegistryPostProcessor
  8. 2017年7月19日晚作业
  9. 计算机基础应用课件,计算机应用基础教程(全套课件).ppt
  10. 仿淘宝、腾讯课堂评分组件 --- Android高级自定义组件
  11. Hive批量删除历史分区
  12. cv2显示图片显蓝色
  13. 运维工程师和网络工程师的差别在哪?到底哪个更有“钱”途?
  14. sqoop:File does not exist:
  15. Leetcode 1218. 最长定差子序列(DAY 47) ---- 动态规划学习期(昨天又没有看书捏 懒狗biss)
  16. 波斯顿房价(lasso、线性回归、留出法、k折交叉验证法)
  17. 数字化转型的失败原因及成功之道
  18. 003--北大考研计算机--考研经验贴
  19. 24.shell中list详解,定义list,获取List的总个数,获取list的某个元素值,将list的每个元素转换成以空格分隔的字符串,空格分隔的字符串转换成list,for循环list
  20. 高端电视选购调查:8成用户放弃OLED选择ULEDX

热门文章

  1. 00-elasticsearch的pom文件
  2. Backbone集合
  3. 全局的过滤器, 进行时间的格式化——所谓的全局过滤器,就是所有的VM实例都共享的 || 如何自定义一个私有的过滤器(局部)
  4. Python 技术篇 - 通过pyminifier库实现源码压缩、混淆、加密保护实例演示,pyminifier的使用方法
  5. 嵌入式C语言代码规范
  6. STM8L之外部中断
  7. [YTU]_2354 (实现复数类中的加运算符重载【C++运算符重载】)
  8. [YTU]_2424 C语言习题 字符串比较
  9. 合并两个有序链表(C++)
  10. 无重复字符的最长子串【哈希算法】-O(n)