您好,登錄后才能下訂單哦!
目的很明確,直接貼代碼(反射一個對象,將屬性存入DataTable中綁定顯示):
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);
}
}
}
}
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。