zoukankan      html  css  js  c++  java
  • 使用反射简化日常操作(转)

    转自:http://www.guaik.com/aspnet/SO44LAVYT5MU9IBM.shtm

    做了这么长时间的开发,书写的代码最无趣,最无聊,而又没有什么价值,却不能不做的是什么?应该就如棉棉讲的,为对象或控件进行赋值的部分了。如:

    1. ddlRecoMember.Text = bean.fd_Key_RecoMemberID.ToString();  
    2. txtRecoSort.Text = bean.fd_Key_RecoSort.ToString();  
    3. txtRecoStartTime.Text = bean.fd_Key_RecoStartTime.ToString("yyyy-MM-dd");  
    4. txtRecoEndTime.Text = bean.fd_Key_RecoEndTime.ToString("yyyy-MM-dd");  
    5. txtRecoLink.Text = bean.fd_Key_RecoLink;  
    ddlRecoMember.Text = bean.fd_Key_RecoMemberID.ToString();txtRecoSort.Text = bean.fd_Key_RecoSort.ToString();txtRecoStartTime.Text = bean.fd_Key_RecoStartTime.ToString("yyyy-MM-dd");txtRecoEndTime.Text = bean.fd_Key_RecoEndTime.ToString("yyyy-MM-dd");txtRecoLink.Text = bean.fd_Key_RecoLink;


            这里重复进行着无价值的劳动,使你不能专心的从事更有价值和核心的工作,那么我们可以不可以避免或减少这类型代码的编写?
            其实可以的。
            如果进行总结,我们可以发现,虽然强大的ASP.NET架构为我们提供了一大堆完美的控件,但,在做编辑功能时,如果没有特殊需求,我们总是在重复使用特定的一小部分,像:TextBox、DropDownList、ListBox、CheckBox、CheckBoxList、RadioButton、RadioButtonList和TextBox。而实体类属性的数据类型就更简单了,像String,DateTime,Boolean和Int32等。
            运用强大的反射功能,我们可以做到把这种代码书写的次数减至最少。
            反射是.NET提供的一种用在运行时刻动态获得程序集的元数据、类信息等资源,可以获得对象接口,动态创建对象,执行相关代码的机制。
            现在准备使用它来完成这些重复劳动。为了从对象中获取或设置属性的值,我们需要运用下面的代码得到属性列表:

    1. Type t = obj.GetType();//obj是Object类型可为任意类型  
    2. PropertyInfo[] props = t.GetProperties();  
    Type t = obj.GetType();//obj是Object类型可为任意类型PropertyInfo[] props = t.GetProperties();


            下面我们定义一个根据属性推断出控件的ID:

    1. public virtual string GetControlID(PropertyInfo prop)  
    2. {  
    3.     string shortName = (prop.Name.Length > 0 && (prop.Name.ToLower().StartsWith("fd") || prop.Name.ToLower().StartsWith("fa"))) ? prop.Name.Substring(6) : prop.Name;  
    4.     string startChar = "txt";  
    5.     if (prop.PropertyType == typeof(bool))  
    6.     {  
    7.         startChar = "chb";  
    8.     }  
    9.     return startChar + shortName;  
    10. }  
    public virtual string GetControlID(PropertyInfo prop){string shortName = (prop.Name.Length > 0 && (prop.Name.ToLower().StartsWith("fd") || prop.Name.ToLower().StartsWith("fa"))) ? prop.Name.Substring(6) : prop.Name;string startChar = "txt";if (prop.PropertyType == typeof(bool)){startChar = "chb";}return startChar + shortName;}


            下面的方法是,从一个控件集合中填充对象:

    1. public virtual void FillByControl(Object obj, Control ctrl)//ctrl是包含有需要赋值的控件  
    2. {  
    3.     if (obj == nullreturn;  
    4.   
    5.     String key = null;  
    6.     Object val = null;  
    7.     Control findCtrl = null;  
    8.     PropertyInfo[] props = GetProperties(obj);  
    9.     foreach (PropertyInfo info in props)  
    10.     {  
    11.         key = GetControlID(info);  
    12.         findCtrl = ctrl.FindControl(key);  
    13.         if (findCtrl != null)  
    14.         {  
    15.             val = GetValue(findCtrl);  
    16.   
    17.             if (info.PropertyType.Name == "Nullable`1")//如果是Nullable类型  
    18.             {  
    19.                 Type baseType = Nullable.GetUnderlyingType(info.PropertyType);  
    20.                 if (!String.IsNullOrEmpty(string.Format("{0}", val)))  
    21.                 {  
    22.                     info.SetValue(obj, Convert.ChangeType(val, baseType), null);  
    23.                 }  
    24.             }  
    25.             else  
    26.             {  
    27.                 if (!info.PropertyType.IsValueType || !String.IsNullOrEmpty(string.Format("{0}", val)))  
    28.                 {  
    29.                     info.SetValue(obj, Convert.ChangeType(val, info.PropertyType), null);  
    30.                 }  
    31.             }  
    32.         }  
    33.     }  
    34. }  
    public virtual void FillByControl(Object obj, Control ctrl)//ctrl是包含有需要赋值的控件{if (obj == null) return;String key = null;Object val = null;Control findCtrl = null;PropertyInfo[] props = GetProperties(obj);foreach (PropertyInfo info in props){key = GetControlID(info);findCtrl = ctrl.FindControl(key);if (findCtrl != null){val = GetValue(findCtrl);if (info.PropertyType.Name == "Nullable`1")//如果是Nullable类型{Type baseType = Nullable.GetUnderlyingType(info.PropertyType);if (!String.IsNullOrEmpty(string.Format("{0}", val))){info.SetValue(obj, Convert.ChangeType(val, baseType), null);}}else{if (!info.PropertyType.IsValueType || !String.IsNullOrEmpty(string.Format("{0}", val))){info.SetValue(obj, Convert.ChangeType(val, info.PropertyType), null);}}}}}


            下面的方法与上面的相反,是从对象中取值来初始化控件

    1. public virtual void Fill2Control(Object obj, Control ctrl)  
    2. {  
    3.     Object val = null;  
    4.     String ctrlId = null;  
    5.     Control findCtrl = null;  
    6.     PropertyInfo[] props = GetProperties(obj);  
    7.   
    8.     foreach (PropertyInfo prop in props)  
    9.     {  
    10.         val = prop.GetValue(obj, null);  
    11.         if (val != null)//如果不为空  
    12.         {  
    13.             ctrlId = GetControlID(prop);  
    14.             findCtrl = ctrl.FindControl(ctrlId);  
    15.             if (findCtrl != null)  
    16.             {  
    17.                 SetValue(findCtrl, val);  
    18.             }  
    19.         }  
    20.     }  
    21. }  
    public virtual void Fill2Control(Object obj, Control ctrl){Object val = null;String ctrlId = null;Control findCtrl = null;PropertyInfo[] props = GetProperties(obj);foreach (PropertyInfo prop in props){val = prop.GetValue(obj, null);if (val != null)//如果不为空{ctrlId = GetControlID(prop);findCtrl = ctrl.FindControl(ctrlId);if (findCtrl != null){SetValue(findCtrl, val);}}}}


            运用上面的代码片段,就可以帮助我们完成对从对象取值赋值控件和从控件取值赋值对象的绝大部分代码了。从上面的代码片断中,我写出了对象与控件间的赋值操作。如果想实现从查询变量中初始化对象也是可以按类似思路实现的。下面是这个类的完整代码:

    1. using System;  
    2. using System.Text;  
    3. using System.Web.UI;  
    4. using System.Collections;  
    5. using System.Collections.Generic;  
    6. using System.Web;  
    7. using System.Reflection;  
    8. using System.Collections.Specialized;  
    9.   
    10. namespace Guaik.Web  
    11. {  
    12.     ///   
    13.     /// 用于对象的填充,由Guaik.com提供  
    14.     ///   
    15.     public class Porter  
    16.     {  
    17.         #region 默认值  
    18.         ///   
    19.         /// 默认的日期  
    20.         ///   
    21.         public readonly static DateTime DefaultDateTime = new DateTime(1900, 1, 1);  
    22.         ///   
    23.         /// 从QueryString中读取Boolean类型为true的值  
    24.         ///   
    25.         public readonly static String BooleanValue = "on";  
    26.         #endregion  
    27.   
    28.         #region 数据缓存  
    29.         private static Hashtable htProperties = new Hashtable();  
    30.   
    31.         ///   
    32.         /// 得到对象的属性列表  
    33.         ///   
    34.         ///   
    35.         ///   
    36.         public static PropertyInfo[] GetProperties(Object obj)  
    37.         {  
    38.             if( obj == null ) return null;  
    39.   
    40.             Type t = obj.GetType();  
    41.             if (!htProperties.ContainsKey(t.FullName))  
    42.             {  
    43.                 htProperties[t.FullName] = t.GetProperties();  
    44.             }  
    45.             return (PropertyInfo[])htProperties[t.FullName];  
    46.         }  
    47.         #endregion  
    48.   
    49.         #region 得到键  
    50.         ///   
    51.         /// 得到查询字符串的键  
    52.         ///   
    53.         ///   
    54.         ///   
    55.         public virtual string GetQueryStringKey(PropertyInfo prop)  
    56.         {  
    57.             if (prop.Name.Length > 6 && prop.Name.ToLower().StartsWith("fd"))  
    58.             {  
    59.                 return prop.Name.Substring(6);  
    60.             }  
    61.             else  
    62.             {  
    63.                 return prop.Name;  
    64.             }  
    65.         }  
    66.   
    67.         ///   
    68.         /// 得到控件的ID  
    69.         ///   
    70.         ///   
    71.         ///   
    72.         public virtual string GetControlID(PropertyInfo prop)  
    73.         {  
    74.             string shortName = (prop.Name.Length > 0 && (prop.Name.ToLower().StartsWith("fd") || prop.Name.ToLower().StartsWith("fa"))) ? prop.Name.Substring(6) : prop.Name;  
    75.             string startChar = "txt";  
    76.             if (prop.PropertyType == typeof(bool))  
    77.             {  
    78.                 startChar = "chb";  
    79.             }  
    80.             return startChar + shortName;  
    81.         }  
    82.         #endregion  
    83.   
    84.         #region 数据填充  
    85.         ///   
    86.         /// 将过滤条件填充到控件下  
    87.         ///   
    88.         ///   
    89.         public virtual void Fill2Control(Object obj, Control ctrl)  
    90.         {  
    91.             Object val = null;  
    92.             String ctrlId = null;  
    93.             Control findCtrl = null;  
    94.             PropertyInfo[] props = GetProperties(obj);  
    95.   
    96.             foreach (PropertyInfo prop in props)  
    97.             {  
    98.                 val = prop.GetValue(obj, null);  
    99.                 if (val != null)//如果不为空  
    100.                 {  
    101.                     ctrlId = GetControlID(prop);  
    102.                     findCtrl = ctrl.FindControl(ctrlId);  
    103.                     if (findCtrl != null)  
    104.                     {  
    105.                         SetValue(findCtrl, val);  
    106.                     }  
    107.                 }  
    108.             }  
    109.         }  
    110.   
    111.         ///   
    112.         /// 从QueryString集合中填充  
    113.         ///   
    114.         public virtual void FillByNameValueCollection(Object obj, NameValueCollection valueCollection)  
    115.         {  
    116.             if (valueCollection == nullreturn;  
    117.   
    118.             String key = null;  
    119.             PropertyInfo[] props = GetProperties(obj);  
    120.             foreach (PropertyInfo info in props)  
    121.             {  
    122.                 key = GetQueryStringKey(info);  
    123.                 if (!String.IsNullOrEmpty(valueCollection[key]))  
    124.                 {  
    125.                     if (info.PropertyType == typeof(bool) && valueCollection[key] == BooleanValue)  
    126.                     {  
    127.                         info.SetValue(obj, (valueCollection[key] == BooleanValue ? true : false), null);  
    128.                     }  
    129.                     else  
    130.                     {  
    131.                         if (info.PropertyType.Name == "Nullable`1")  
    132.                         {  
    133.                             Type baseType = Nullable.GetUnderlyingType(info.PropertyType);  
    134.                             info.SetValue(obj, Convert.ChangeType(valueCollection[key], baseType), null);  
    135.                         }  
    136.                         else  
    137.                         {  
    138.                             info.SetValue(obj, Convert.ChangeType(valueCollection[key], info.PropertyType), null);  
    139.                         }  
    140.                     }  
    141.                 }  
    142.             }  
    143.         }  
    144.   
    145.         ///   
    146.         /// 设置控件的值  
    147.         ///   
    148.         ///   
    149.         ///   
    150.         public virtual void SetValue(Control ctrl, Object val)  
    151.         {  
    152.             if (ctrl is ITextControl)//TextBox, DropDownList, ListBox...  
    153.             {  
    154.                 ((ITextControl)ctrl).Text = val.ToString();  
    155.             }  
    156.             else if (ctrl is ICheckBoxControl)//CheckBox  
    157.             {  
    158.                 ((ICheckBoxControl)ctrl).Checked = (bool)val;  
    159.             }  
    160.         }  
    161.   
    162.         ///   
    163.         /// 得到控件的值  
    164.         ///   
    165.         ///   
    166.         ///   
    167.         public virtual Object GetValue(Control ctrl)  
    168.         {  
    169.             object val = null;  
    170.             if (ctrl is ITextControl)//TextBox, DropDownList, ListBox...  
    171.             {  
    172.                 val = ((ITextControl)ctrl).Text;  
    173.             }  
    174.             else if (ctrl is ICheckBoxControl)//CheckBox  
    175.             {  
    176.                 val = ((ICheckBoxControl)ctrl).Checked;  
    177.             }  
    178.             return val;  
    179.         }  
    180.   
    181.         public virtual void FillByControl(Object obj, Control ctrl)  
    182.         {  
    183.             if (obj == nullreturn;  
    184.   
    185.             String key = null;  
    186.             Object val = null;  
    187.             Control findCtrl = null;  
    188.             PropertyInfo[] props = GetProperties(obj);  
    189.             foreach (PropertyInfo info in props)  
    190.             {  
    191.                 key = GetControlID(info);  
    192.                 findCtrl = ctrl.FindControl(key);  
    193.                 if (findCtrl != null)  
    194.                 {  
    195.                     val = GetValue(findCtrl);  
    196.   
    197.                     if (info.PropertyType.Name == "Nullable`1")//如果是Nullable类型  
    198.                     {  
    199.                         Type baseType = Nullable.GetUnderlyingType(info.PropertyType);  
    200.                         if (!String.IsNullOrEmpty(string.Format("{0}", val)))  
    201.                         {  
    202.                             info.SetValue(obj, Convert.ChangeType(val, baseType), null);  
    203.                         }  
    204.                     }  
    205.                     else  
    206.                     {  
    207.                         if (!info.PropertyType.IsValueType || !String.IsNullOrEmpty(string.Format("{0}", val)))  
    208.                         {  
    209.                             info.SetValue(obj, Convert.ChangeType(val, info.PropertyType), null);  
    210.                         }  
    211.                     }  
    212.                 }  
    213.             }  
    214.         }  
    215.         #endregion  
    216.     }  
    217. }  
    using System;using System.Text;using System.Web.UI;using System.Collections;using System.Collections.Generic;using System.Web;using System.Reflection;using System.Collections.Specialized;namespace Guaik.Web{/// /// 用于对象的填充,由Guaik.com提供/// public class Porter{    #region 默认值    ///     /// 默认的日期    ///     public readonly static DateTime DefaultDateTime = new DateTime(1900, 1, 1);    ///     /// 从QueryString中读取Boolean类型为true的值    ///     public readonly static String BooleanValue = "on";    #endregion    #region 数据缓存    private static Hashtable htProperties = new Hashtable();    ///     /// 得到对象的属性列表    ///     ///     ///     public static PropertyInfo[] GetProperties(Object obj)    {        if( obj == null ) return null;        Type t = obj.GetType();        if (!htProperties.ContainsKey(t.FullName))        {            htProperties[t.FullName] = t.GetProperties();        }        return (PropertyInfo[])htProperties[t.FullName];    }    #endregion    #region 得到键    ///     /// 得到查询字符串的键    ///     ///     ///     public virtual string GetQueryStringKey(PropertyInfo prop)    {        if (prop.Name.Length > 6 && prop.Name.ToLower().StartsWith("fd"))        {            return prop.Name.Substring(6);        }        else        {            return prop.Name;        }    }    ///     /// 得到控件的ID    ///     ///     ///     public virtual string GetControlID(PropertyInfo prop)    {        string shortName = (prop.Name.Length > 0 && (prop.Name.ToLower().StartsWith("fd") || prop.Name.ToLower().StartsWith("fa"))) ? prop.Name.Substring(6) : prop.Name;        string startChar = "txt";        if (prop.PropertyType == typeof(bool))        {            startChar = "chb";        }        return startChar + shortName;    }    #endregion    #region 数据填充    ///     /// 将过滤条件填充到控件下    ///     ///     public virtual void Fill2Control(Object obj, Control ctrl)    {        Object val = null;        String ctrlId = null;        Control findCtrl = null;        PropertyInfo[] props = GetProperties(obj);        foreach (PropertyInfo prop in props)        {            val = prop.GetValue(obj, null);            if (val != null)//如果不为空            {                ctrlId = GetControlID(prop);                findCtrl = ctrl.FindControl(ctrlId);                if (findCtrl != null)                {                    SetValue(findCtrl, val);                }            }        }    }    ///     /// 从QueryString集合中填充    ///     public virtual void FillByNameValueCollection(Object obj, NameValueCollection valueCollection)    {        if (valueCollection == null) return;        String key = null;        PropertyInfo[] props = GetProperties(obj);        foreach (PropertyInfo info in props)        {            key = GetQueryStringKey(info);            if (!String.IsNullOrEmpty(valueCollection[key]))            {                if (info.PropertyType == typeof(bool) && valueCollection[key] == BooleanValue)                {                    info.SetValue(obj, (valueCollection[key] == BooleanValue ? true : false), null);                }                else                {                    if (info.PropertyType.Name == "Nullable`1")                    {                        Type baseType = Nullable.GetUnderlyingType(info.PropertyType);                        info.SetValue(obj, Convert.ChangeType(valueCollection[key], baseType), null);                    }                    else                    {                        info.SetValue(obj, Convert.ChangeType(valueCollection[key], info.PropertyType), null);                    }                }            }        }    }    ///     /// 设置控件的值    ///     ///     ///     public virtual void SetValue(Control ctrl, Object val)    {        if (ctrl is ITextControl)//TextBox, DropDownList, ListBox...        {            ((ITextControl)ctrl).Text = val.ToString();        }        else if (ctrl is ICheckBoxControl)//CheckBox        {            ((ICheckBoxControl)ctrl).Checked = (bool)val;        }    }    ///     /// 得到控件的值    ///     ///     ///     public virtual Object GetValue(Control ctrl)    {        object val = null;        if (ctrl is ITextControl)//TextBox, DropDownList, ListBox...        {            val = ((ITextControl)ctrl).Text;        }        else if (ctrl is ICheckBoxControl)//CheckBox        {            val = ((ICheckBoxControl)ctrl).Checked;        }        return val;    }    public virtual void FillByControl(Object obj, Control ctrl)    {        if (obj == null) return;        String key = null;        Object val = null;        Control findCtrl = null;        PropertyInfo[] props = GetProperties(obj);        foreach (PropertyInfo info in props)        {            key = GetControlID(info);            findCtrl = ctrl.FindControl(key);            if (findCtrl != null)            {                val = GetValue(findCtrl);                if (info.PropertyType.Name == "Nullable`1")//如果是Nullable类型                {                    Type baseType = Nullable.GetUnderlyingType(info.PropertyType);                    if (!String.IsNullOrEmpty(string.Format("{0}", val)))                    {                        info.SetValue(obj, Convert.ChangeType(val, baseType), null);                    }                }                else                {                    if (!info.PropertyType.IsValueType || !String.IsNullOrEmpty(string.Format("{0}", val)))                    {                        info.SetValue(obj, Convert.ChangeType(val, info.PropertyType), null);                    }                }            }        }    }    #endregion}}


            运用这个代码的示例也非常简单,假设有类User,需要为divMain下的控件赋值,可以这样做:

    1. User bean = new User();  
    2. Porter porter = new Porter();  
    3.   
    4. porter.FillByControl(bean, divMain);//从divMain下的控件初始化bean对象。  
    5. //porter.File2Control(bean, divMain);//把bean对象的值赋值给divMain下的控件 
  • 相关阅读:
    软件测试的术语及解释总结
    测试工具
    数据库客户端连接
    应用程序发生错误怎么修改
    软件测试容易忽略的缺陷
    LR中错误解决方法
    LR结果分析2
    LR结果分析
    Hive
    zookeeper
  • 原文地址:https://www.cnblogs.com/kinpauln/p/1756887.html
Copyright © 2011-2022 走看看