怎么利用反射在一个泛型方法中传入一个 DataTable 返回一个集合如 public IList<T> GetListByDataTable(Type t,DataTable table)
{
...............这里面怎么写啊
}
谢谢给段简单的代码哈 t 是一个自定义的类
{
...............这里面怎么写啊
}
谢谢给段简单的代码哈 t 是一个自定义的类
解决方案 »
- C#有比hashtable更效率或更优秀的东西吗?
- C# winform程序每当使用主题的时候就会出现超出最大容量的问题。
- foreach 问题
- asp在框架frameset中session丢失的问题,在线等急!!!!!
- TCP通讯接口说明(能说多少说多少,聚集思路)
- c# udp时快时慢的问题,请高手指点。。。。。。
- 一个关于显示当前日期小问题,请各位热心回答
- WebForm的TextBox没有KeyDown事件,这怎么办?
- 水印加到原图下面怎么实现(文字的)
- 请问vc.net和c#有什么不同?vc 7.0是不是vc.net?
- 任意字符的正则????高手指点
- [C#]用Image或Bitmap对象获取图像的色深?(不使用Palette)
就简单写个例子,没什么意义,
运行弹出对话框"123"
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;namespace WindowsFormsApplication12
{
public partial class Form1 : Form
{
public class T
{
public int X;
} public Form1()
{
InitializeComponent(); DataTable DT = new DataTable();
DT.Columns.Add("X", typeof(T));
T NewT = new T();
NewT.X = 123;
DT.Rows.Add(new Object[] { NewT });
IList<T> LT = GetListByDataTable(typeof(T), DT);
foreach (T t in LT)
MessageBox.Show(t.X.ToString());
} public IList<T> GetListByDataTable(Type t, DataTable table)
{
List<T> LT = new List<T>();
foreach (DataRow DR in table.Rows)
{
T tt = new T();
tt.X = (int)t.GetField("X").GetValue(DR[0]);
LT.Add(tt);
}
return LT;
}
}
}
public static IList<T> ConvertToModel(DataTable dt)
{
IList<T> lst= new List<T>();
Type type = typeof(T);
string tempName = "";
foreach (DataRow dr in dt.Rows)
{
T t = new T();
PropertyInfo[] propertys = t.GetType().GetProperties();
foreach (PropertyInfo pi in propertys)
{
tempName = pi.Name;
if (dt.Columns.Contains(tempName))
{
if (!pi.CanWrite) continue;
object value = dr[tempName];
if (value != DBNull.Value)
pi.SetValue(t, value, null);
}
}
lst.Add(t);
}
return ts;
}
}
{ IList<T> list = new List<T>();
T t = default(T);
PropertyInfo[] propertypes = null;
string tempName = string.Empty; foreach (DataRow row in table.Rows)
{
t = Activator.CreateInstance<T>(); propertypes = t.GetType().GetProperties(); foreach (PropertyInfo pro in propertypes)
{
tempName = pro.Name;
if (table.Columns.Contains(tempName))
{
object value = row[tempName];
pro.SetValue(t, value, null); } }
list.Add(t);
} return list;
}