通过执行缓慢的属性进行循环的反射

本文关键字:循环 反射 属性 执行 缓慢 | 更新日期: 2023-09-27 18:17:18

我正在设计一个通过反射将对象映射到页面的系统,方法是查看字段名和属性名,然后尝试设置控件的值。问题是系统需要大量的时间来完成。我希望有人能帮我加快一点速度

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,循环属性一次,不如将它们放入字典中,然后在循环控件时使用该字典