重庆分公司,新征程启航
为企业提供网站建设、域名注册、服务器等服务
目的很明确,直接贴代码(反射一个对象,将属性存入DataTable中绑定显示):
成都创新互联公司主要从事成都网站制作、网站建设、外贸网站建设、网页设计、企业做网站、公司建网站等业务。立足成都服务恭城,十载网站建设经验,价格优惠、服务专业,欢迎来电咨询建站服务:13518219792
public static DataTable CreateDataTabele( object obj)
{
DataTable dt = new DataTable();
DataColumn did = new DataColumn("ID", Type.GetType("System.Int32"));//ID
DataColumn dParentID = new DataColumn("ParentID", Type.GetType("System.Int32"));//父节点ID
DataColumn dNodeName = new DataColumn("Name", Type.GetType("System.String"));//节点名
DataColumn dNodeCaption = new DataColumn("Caption", Type.GetType("System.String"));//节点中文名
DataColumn dCanAdded = new DataColumn("CanAdded", Type.GetType("System.Boolean"));//是否包含子节点
DataColumn dNodeProperty = new DataColumn("NodeProperty", Type.GetType("System.String"));//属性
DataColumn dType = new DataColumn("NodeType", Type.GetType("System.String"));
DataColumn dChildName = new DataColumn("NodeChildName", Type.GetType("System.String"));
DataColumn dValue = new DataColumn("NodeValue", Type.GetType("System.Object"));
dt.Columns.AddRange(new DataColumn[] { dParentID, did, dNodeName, dNodeCaption, dCanAdded, dNodeProperty , dType, dChildName,dValue });
int id = 1;
int pid = 0;
DataRow dw = dt.NewRow();
dw["ID"] = id;
dw["ParentID"] = pid++;
dw["Name"] = "FormConfig";
dw["Caption"] = "XXX节点";
dw["CanAdded"] = false;
dt.Rows.Add(dw);
ReflectObject(obj, ref dt,ref id, pid, 0);
return dt;
}
///递归反射节点
private static void ReflectObject(object obj, ref DataTable dt, ref int id, int pid, int pID)
{
if (obj == null) return;
Type type = obj.GetType();
foreach (PropertyInfo pi in type.GetProperties())
{
DataRow dw = dt.NewRow();
dw["ID"] = ++id;
dw["ParentID"] = pid;
dw["Name"] = pi.Name.ToString();
if ((pi.GetCustomAttributes(true)).Count() > 0) dw["Caption"] = ((DescriptionAttribute)(pi.GetCustomAttributes(true))?[0]).Description;
dw["CanAdded"] = false;
if (pi.PropertyType.Name.ToLower().Equals("list`1"))
{
dw["CanAdded"] = true;
}
dt.Rows.Add(dw);
pID = id ;
if (!(pi.PropertyType).IsPrimitive)
{
if (pi.PropertyType.Name != "String")
{
var proValue = pi.GetValue(obj, null);
if (proValue == null)
{
////个人使用的单例创建对象 于读者无关
if(ToolHelper._dicCreate.ContainsKey(pi.PropertyType.Name))
{
proValue = ToolHelper._dicCreate[pi.PropertyType.Name].Invoke();
}
pi.SetValue(obj, proValue, null);
}
ReflectObject(proValue, ref dt, ref id, pID, 0);
}
}
}
}