下面的代码是利用反射获取类或结构的Field和Property,其中,需要注意的是,当使用反射为结构的Field设置值时,不能使用SetValue方法,而是使用SetValueDirect(),FieldInfo.SetValue (Not work with Structure),具体如下:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Reflection;
using System.Data;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
DataTable dt = GetFiledNames();
for (int i = 0; i < dt.Columns.Count; i++)
{
Console.WriteLine(dt.Columns[i].Caption);
}
dt.Rows[1][0] = 1;
dt.Rows[1][1] = 2;
Point p = GetFieldValues(dt);
Console.WriteLine("{0},{1}", p.x, p.y);
Console.Read();
}
private static DataTable GetPropertyNames()
{
PropertyInfo[] propertyInfos;
propertyInfos = typeof(Point).GetProperties();
DataTable dt = new DataTable();
int i = 0;
foreach (PropertyInfo item in propertyInfos)
{
dt.Columns.Add();
dt.Columns[i].Caption = item.Name;
dt.Columns[i].DataType = item.PropertyType;
i++;
}
for (int j = 0; j < 2; j++)
{
DataRow dr = dt.NewRow();
dt.Rows.Add(dr);
}
return dt;
}
private static Point GetPropertyValues(DataTable dt)
{
PropertyInfo[] propertyInfos;
propertyInfos = typeof(Point).GetProperties();
Point p = new Point();
for (int i = 0; i < dt.Columns.Count; i++)
{
propertyInfos[i].SetValue(p, dt.Rows[1][i], null);
}
return p;
}
private static DataTable GetFiledNames()
{
FieldInfo[] fieldInfos;
fieldInfos = typeof(Point).GetFields();
DataTable dt = new DataTable();
int i = 0;
foreach (FieldInfo item in fieldInfos)
{
dt.Columns.Add();
dt.Columns[i].Caption = item.Name;
dt.Columns[i].DataType = item.FieldType;
i++;
}
for (int j = 0; j < 2; j++)
{
DataRow dr = dt.NewRow();
dt.Rows.Add(dr);
}
return dt;
}
private static Point GetFieldValues(DataTable dt)
{
FieldInfo[] fieldInfos;
fieldInfos = typeof(Point).GetFields();
Point p = new Point();
for (int i = 0; i < dt.Columns.Count; i++)
{
fieldInfos[i].SetValueDirect(__makeref(p), dt.Rows[1][i]);
}
return p;
}
}
public struct Point
{
public int x;
public int y;
//public int x { get; set; }
//public int y { get; set; }
}
}
参考资料:
http://msdn.microsoft.com/zh-cn/library/system.data.datatable.newrow(VS.80).aspx