C# 反射以循环执行缓慢的属性
我正在设计一个通过反射将对象映射到页面的系统,方法是查看字段名和属性名,然后尝试设置控件的值。问题是这个系统需要花费大量的时间来完成。我希望有人能帮我加快速度C# 反射以循环执行缓慢的属性,c#,asp.net,reflection,recursion,C#,Asp.net,Reflection,Recursion,我正在设计一个通过反射将对象映射到页面的系统,方法是查看字段名和属性名,然后尝试设置控件的值。问题是这个系统需要花费大量的时间来完成。我希望有人能帮我加快速度 public static void MapObjectToPage(this object obj, Control parent) { Type type = obj.GetType(); foreach(PropertyInfo info in type.GetProperties(BindingFlags.Publ
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;
但是,这违背了这样做的目的,即我们可以将对象映射到页面,而无需手动设置所有值
我已经确定的两个主要瓶颈是foreach循环,因为它通过每个控件/属性循环,在我的一些对象中有20个左右的属性而不是循环N*M,循环属性一次,将它们放入字典,然后在循环控件时使用该字典而不是循环N*M,循环属性将它们放入字典,然后在循环控件时使用它。多少是“大量时间”?你试过分析它吗?在一个有10个控件和一个有20个属性的对象的页面上,加载需要4.3分钟@I4V,好主意,我不知道为什么我没有想到:S@I4V,效果很好:加载时间缩短到3秒。如果你想把它作为一个答案,这样我就可以接受它,那太棒了!