【发布时间】:2013-06-02 13:37:57
【问题描述】:
我正在设计一个通过反射将对象映射到页面的系统,方法是查看字段名称和属性名称,然后尝试设置控件的值。问题是系统需要大量时间才能完成。我希望有人可以帮助加快速度
public static void MapObjectToPage(this object obj, Control parent) {
Type type = obj.GetType();
foreach(PropertyInfo info in type.GetProperties(BindingFlags.Public | BindingFlags.Instance)){
foreach (Control c in parent.Controls ) {
if (c.ClientID.ToLower() == info.Name.ToLower()) {
if (c.GetType() == typeof(TextBox) && info.GetValue(obj, null) != null)
{
((TextBox)c).Text = info.GetValue(obj, null).ToString();
}
else if (c.GetType() == typeof(HtmlInputText) && info.GetValue(obj, null) != null)
{
((HtmlInputText)c).Value = info.GetValue(obj, null).ToString();
}
else if (c.GetType() == typeof(HtmlTextArea) && info.GetValue(obj, null) != null)
{
((HtmlTextArea)c).Value = info.GetValue(obj, null).ToString();
}
//removed control types to make easier to read
}
// Now we need to call itself (recursive) because
// all items (Panel, GroupBox, etc) is a container
// so we need to check all containers for any
// other controls
if (c.HasControls())
{
obj.MapObjectToPage(c);
}
}
}
}
我意识到我可以通过
手动执行此操作textbox.Text = obj.Property;
但是,这违背了我们可以将对象映射到页面而无需所有手动设置值的目的。
我发现的 2 个主要瓶颈是 foreach 循环,因为它循环遍历每个控件/属性,并且在我的一些对象中有 20 个左右的属性
【问题讨论】:
-
循环属性不是循环 N*M,而是将它们放入字典中,然后在循环控件时使用它。
-
“大量时间”是多少?你试过分析它吗?
-
在一个有 10 个控件的页面和一个有 20 个属性的对象上,加载需要 4.3 分钟。 @I4V,好主意,我不知道为什么我没想到:S
-
@I4V,效果很好:S 加载时间缩短至 3 秒。如果您想将其发布为答案以便我接受,那就太好了!
标签: c# asp.net reflection recursion