目的很明確,直接貼代碼(反射一個(gè)對(duì)象,將屬性存入DataTable中綁定顯示):
成都創(chuàng)新互聯(lián)公司主要從事成都網(wǎng)站制作、網(wǎng)站建設(shè)、外貿(mào)網(wǎng)站建設(shè)、網(wǎng)頁(yè)設(shè)計(jì)、企業(yè)做網(wǎng)站、公司建網(wǎng)站等業(yè)務(wù)。立足成都服務(wù)恭城,十載網(wǎng)站建設(shè)經(jīng)驗(yàn),價(jià)格優(yōu)惠、服務(wù)專業(yè),歡迎來(lái)電咨詢建站服務(wù):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"));//父節(jié)點(diǎn)ID
DataColumn dNodeName = new DataColumn("Name", Type.GetType("System.String"));//節(jié)點(diǎn)名
DataColumn dNodeCaption = new DataColumn("Caption", Type.GetType("System.String"));//節(jié)點(diǎn)中文名
DataColumn dCanAdded = new DataColumn("CanAdded", Type.GetType("System.Boolean"));//是否包含子節(jié)點(diǎn)
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節(jié)點(diǎn)";
dw["CanAdded"] = false;
dt.Rows.Add(dw);
ReflectObject(obj, ref dt,ref id, pid, 0);
return dt;
}
///遞歸反射節(jié)點(diǎn)
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)
{
////個(gè)人使用的單例創(chuàng)建對(duì)象 于讀者無(wú)關(guān)
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);
}
}
}
}