问题说明: |
|
|
---|---|---|
解决方法: |
|
public class CollectionHelper
{
private static ArrayList Fill(int pID, int level, ArrayList list)
{
ArrayList returnList = new ArrayList();
foreach(object obj in list)
{
int typePID = (int)ReflectionUtil.GetProperty(obj, "PID");
int typeID = (int)ReflectionUtil.GetProperty(obj, "ID");
string typeName = ReflectionUtil.GetProperty(obj, "Name") as string;
if(pID == typePID)
{
string newName = new string('-', level * 4) + typeName;
ReflectionUtil.SetProperty(obj, "Name", newName);
returnList.Add(obj);
returnList.AddRange(Fill(typeID, level+1, list));
}
}
return returnList;
}
/// <summary>
/// 生成有层次结构的列表
/// </summary>
/// <param name="list">具有Name,ID,PID成员的任何集合</param>
/// <returns></returns>
public static ArrayList GetTreeItems(ArrayList list)
{
return Fill(-1, 0, list);
}
}
{
private static ArrayList Fill(int pID, int level, ArrayList list)
{
ArrayList returnList = new ArrayList();
foreach(object obj in list)
{
int typePID = (int)ReflectionUtil.GetProperty(obj, "PID");
int typeID = (int)ReflectionUtil.GetProperty(obj, "ID");
string typeName = ReflectionUtil.GetProperty(obj, "Name") as string;
if(pID == typePID)
{
string newName = new string('-', level * 4) + typeName;
ReflectionUtil.SetProperty(obj, "Name", newName);
returnList.Add(obj);
returnList.AddRange(Fill(typeID, level+1, list));
}
}
return returnList;
}
/// <summary>
/// 生成有层次结构的列表
/// </summary>
/// <param name="list">具有Name,ID,PID成员的任何集合</param>
/// <returns></returns>
public static ArrayList GetTreeItems(ArrayList list)
{
return Fill(-1, 0, list);
}
}
public sealed class ReflectionUtil
{
private ReflectionUtil()
{ }
public static BindingFlags bf = BindingFlags.DeclaredOnly | BindingFlags.Public |
BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Static;
public static void SetProperty(object obj, string name, object value)
{
PropertyInfo fi = obj.GetType().GetProperty(name, bf);
fi.SetValue(obj, value,null);
}
public static object GetProperty(object obj, string name)
{
PropertyInfo fi = obj.GetType().GetProperty(name, bf);
return fi.GetValue(obj,null);
}
}
{
private ReflectionUtil()
{ }
public static BindingFlags bf = BindingFlags.DeclaredOnly | BindingFlags.Public |
BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Static;
public static void SetProperty(object obj, string name, object value)
{
PropertyInfo fi = obj.GetType().GetProperty(name, bf);
fi.SetValue(obj, value,null);
}
public static object GetProperty(object obj, string name)
{
PropertyInfo fi = obj.GetType().GetProperty(name, bf);
return fi.GetValue(obj,null);
}
}
效果图如下