• 【转载】用反射来解决字段多带来的烦恼


    文章是我转载的,地址是:
    http://www.cnblogs.com/snryang/archive/2008/03/22/1117974.html

    做项目开发的时候,大家应该经常都会遇到一个表里面的很多个字段的情况吧.在之前我接触的一个项目,有一个表有20多个字段.要向表中添加记录,和将一条数据绑定到页面上都要写很多代码.如:

    下面是一个用户表的添加
            User user = new User();
            user.Name = this.txt_Name.Text; 
            user.Remark = this.txt_Remark.Text;
            user.Age = int.Parse(this.txt_Age.Text);
            user.Type=this.txt_Type.SelectedValue; 
            user.Time=DateTime.Parse(this.txt_Time.Text);
            new Test().SaveOrUpdate(user);
    将表里面的数据绑定到控件里面如下
            User user=(User) new test().Get(typeof(User),"1");
            txt_Name.Text=user.Name;
            txt_Remark.Text=user.Remark;
            txt_Age.Text=user.Age.ToString();
            txt_Type.SelectedValue=txt_Type.Items.FindByValue(user.Type);
            txt_Time.Text=User.Time.ToString("yyyy-MM-dd");
    上面的列子,数据类型不对我们得进行转换,下拉列表还要进行绑定.当然字段比较少,还不容易怎么出错,如果字段多了,这样一个一个的写太老火了,而且还容易忘记一些,或者把一些数据绑定错,或者忘了ToString().

    思路是这样的: 
    一、对于网页中控件的命名规为 "txt_实体类的字段名";
    二、遍历页面中的所有控件,使用反射将控件的值赋给对象。和将对象的属性值绑定到控件上。

    下面是要用到的一些方法


        /**////  <summary>
        /// 字符串首字母大写
        ///  </summary>
        ///  <param name="s"> </param>
        ///  <returns> </returns>
        public static string ToProperCase(string s)
        {
            string revised = "";
            if (s.Length > 0)
            {
                revised = s.Trim();
                revised = revised.Substring(0, 1).ToUpper() + revised.Substring(1).ToLower();
            }
            return revised;
        }

        /**////  <summary>
        /// 设置对象属性的值
        ///  </summary>
        public static void SetProperty(object obj, string name, object value)
        {
            PropertyInfo propertyInfo = obj.GetType().GetProperty(name);
            object objValue = Convert.ChangeType(value, propertyInfo.PropertyType);
            propertyInfo.SetValue(obj, objValue, null);
        }
        
        /**////  <summary>
        /// 获取对象属性的值
        ///  </summary>
        public static object GetProperty(object obj, string name)
        {
            //bindingFlags
            PropertyInfo propertyInfo = obj.GetType().GetProperty(name);
            return propertyInfo.GetValue(obj, null);
        }
    将控件的值绑定到对象上面。


             for (int i = 0; i  < Page.Controls.Count; i++)
            {
                SetControlValue(Controls[i], "txt_",ref user);  
            }
        /**////  <summary>
        /// 设置对象的值
        ///  </summary>
        private void SetObjectValue(Control page, string str,ref object obj)
        {
            foreach (Control content in page.Controls)
            {
                if (content.Controls.Count > 0)
                {
                    SetObjectValue(content, str,ref obj);
                }
                if (content.ID != null)
                 {
                     string contentID = content.ID.ToLower();
                    if (contentID.Replace(str, "") != contentID.ToLower())
                    {
                        SetProperty(obj, ToProperCase(contentID.Replace(str, "")),
                                                       GetProperty(content,"Text")
                                                   );
                    }
                }
            }
        }
    (上面的Text是TextBox控件的属性,对于下拉列表框也可以使用这个属性获取选定项的值,所以就不用去判断了,最开始我还去判断类型:)

    将对象的值绑定到控件上面


            for (int i = 0; i  < Page.Controls.Count; i++)
            {
                SetControlValue(Controls[i], "txt_", user);
            }

    /**////  <summary>
        /// 设置控件的值
        ///  </summary>
        private void SetControlValue(Control page, string str, object obj)
        {
            foreach (Control content in page.Controls)
            {
                if (content.Controls.Count > 0)
                {
                    SetControlValue(content, str, obj);
                }
                if (content.ID != null)
                {
                    string contentID = content.ID.ToLower();
                    if (contentID.Replace(str, "") != contentID.ToLower())
                    {
                        if (content.GetType() != typeof(DropDownList))
                        {
                            SetProperty(content, "Text",
                                                        GetProperty(obj, ToProperCase(contentID.Replace(str, "")))
                                                       );
                        }
                        else
                        {
                            SetDropDownListItem((DropDownList)content, (string)ReflectionUtil.GetProperty(obj, ToProperCase(contentID.Replace(str, ""))));
                        }
                    }
                }
            } 
        }
  • 相关阅读:
    debian配置apache2.4配置虚拟主机遇到的问题
    Javascript关于attachEvent和addEventListener区别与兼容写法
    图解linux下top命令的使用
    idea报错:java 不支持发行版本5
    java-访问权限
    IDEA图标含义
    IDEA生成UML类图
    idea快捷键
    idea同时运行两个main()
    idea关闭vim编辑模式
  • 原文地址:https://www.cnblogs.com/smallfa/p/1119568.html
Copyright © 2020-2023  润新知