标签:
一:反射的定义
审查元数据并收集关于它的类型信息的能力。元数据(编译以后的最基本数据单元)就是一大堆的表,当编译程序集或者模块时,编译器会创建一个类定义表,一个字段定义表,和一个方法定义表等。
System.reflection命名空间包含的几个类,允许你反射(解析)这些元数据表的代码
  System.Reflection.Assembly 
  System.Reflection.MemberInfo
  System.Reflection.EventInfo
  System.Reflection.FieldInfo
  System.Reflection.MethodBase
  System.Reflection.ConstructorInfo
  System.Reflection.MethodInfo
  System.Reflection.PropertyInfo
  System.Type   
层次模型:
  
二:获取类型信息:
 1         class MyClass
 2         {
 3             public string m;
 4             public void test() { }
 5             public int MyProperty { get; set; }
 6         }
 7 
 8         //获取类型信息
 9         protected void Button1_Click(object sender, EventArgs e)
10         {
11             Type type = typeof(MyClass);
12             Response.Write("类型名:" + type.Name);
13             Response.Write("<br/>");
14             Response.Write("类全名:" + type.FullName);
15             Response.Write("<br/>");
16             Response.Write("命名空间名:" + type.Namespace);
17             Response.Write("<br/>");
18             Response.Write("程序集名:" + type.Assembly);
19             Response.Write("<br/>");
20             Response.Write("模块名:" + type.Module);
21             Response.Write("<br/>");
22             Response.Write("基类名:" + type.BaseType);
23             Response.Write("<br/>");
24             Response.Write("是否类:" + type.IsClass);
25             Response.Write("<br/>");
26             Response.Write("类的公共成员:");
27             Response.Write("<br/>");
28             MemberInfo[] memberInfos = type.GetMembers();//得到所有公共成员
29             foreach (var item in memberInfos)
30             {
31                 Response.Write(string.Format("{0}:{1}", item.MemberType, item));
32                 Response.Write("<br/>");
33             }
34         }
三:获取程序集信息
| protectedvoidButton2_Click(objectsender, EventArgs e){    //获取当前执行代码的程序集    Assembly assem = Assembly.GetExecutingAssembly();    Response.Write("程序集全名:"+assem.FullName);    Response.Write("<br/>");    Response.Write("程序集的版本:"+assem.GetName().Version);    Response.Write("<br/>");    Response.Write("程序集初始位置:"+assem.CodeBase);    Response.Write("<br/>");    Response.Write("程序集位置:"+assem.Location);    Response.Write("<br/>");    Response.Write("程序集入口:"+assem.EntryPoint);    Response.Write("<br/>");    Type[] types = assem.GetTypes();    Response.Write("程序集下包含的类型:");    foreach(varitem intypes)    {        Response.Write("<br/>");        Response.Write("类:"+item.Name);    }}<br> | 
四:反射调用方法
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | protectedvoidPage_Load(objectsender, EventArgs e) {       System.Reflection.Assembly ass = Assembly.LoadFrom(AppDomain.CurrentDomain.BaseDirectory+"bin\\WebApplication1.dll"); //加载DLL     System.Type t = ass.GetType("WebApplication1.MainPage");//获得类型       stringname=typeof(MainPage).AssemblyQualifiedName;     System.Type t1 = Type.GetType(name);System.Type t2 = typeof(MainPage);     objecto = System.Activator.CreateInstance(t);//创建实例       System.Reflection.MethodInfo mi = t.GetMethod("RunJs1");//获得方法       mi.Invoke(o, newobject[] { this.Page, "alert(‘测试反射机制‘)"});//调用方法       System.Reflection.MethodInfo mi1 = t.GetMethod("RunJs");     mi1.Invoke(t, newobject[] { this.Page, "alert(‘测试反射机制1‘)"});//调用方法 }<br> | 
五:反射调用用户/自定义控件
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 |        protectedoverridevoidOnInit(EventArgs e)        {              //生成控件              CreateControl();            base.OnInit(e);        }        privatevoidCreateControl()        {            Table tb = newTable();            TableRow dr = newTableRow();            TableCell cell = newTableCell();            Control c = <span style="color: #ff0000;">LoadControl("WebUserControl1.ascx");</span>            cell.Controls.Add(c);            dr.Cells.Add(cell);            tb.Rows.Add(dr);            this.PlaceHolder1.Controls.Add(tb);        }        protectedvoidButton1_Click(objectsender, EventArgs e)        {            foreach(TableRow tr inPlaceHolder1.Controls[0].Controls)            {                foreach(TableCell tc intr.Controls)                {                    foreach(Control ctl intc.Controls)                    {                        if(ctl isUserControl)                        {                            Type type = ctl.GetType();                            System.Reflection.MethodInfo methodInfo = type.GetMethod("GetResult");                            stringselectedValue = string.Concat(methodInfo.Invoke(ctl, newobject[] { }));                            Response.Write(selectedValue);                            break;                        }                    }                }            }        }<br> | 
六:反射实现工厂模式
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 | publicpartialclass反射 : System.Web.UI.Page    {        protectedvoidPage_Load(objectsender, EventArgs e)        {            stringtypeName = typeof(TestClass).AssemblyQualifiedName;            ITestInterface iface = RawGenericFactory.Create<ITestInterface>(typeName);            stringresult = iface.doSomething();            Response.Write(result);        }    }    publicstaticclassRawGenericFactory    {        publicstaticT Create<T>(stringtypeName)        {            //Activator.CreateInstance 反射 根据程序集创建借口或者类            //Type.GetType() 根据名称获得程序集信息            //typeof(ConcertProduct).AssemblyQualifiedName            //_iproduct.GetType().AssemblyQualifiedName            return(T)Activator.CreateInstance(Type.GetType(typeName));        }    }    publicinterfaceITestInterface    {        stringdoSomething();    }    publicclassTestClass : ITestInterface    {        publicintId { get; set; }        publicoverridestringToString()        {            returnId.ToString();        }        publicstringdoSomething()        {            return"ok";        }    }<br> | 
七:自定义ORM框架
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 |   [Orm.Table("TestORM")]        publicclassTestORM        {              [Orm.Colum("Id",DbType.Int32)]            publicintId { get; set; }            [Orm.Colum("UserName", DbType.String)]            publicstringUserName { get; set; }            [Orm.Colum("Password", DbType.String)]            publicstringPassword { get; set; }            [Orm.Colum("CreatedTime", DbType.DateTime)]            publicDateTime CreatedTime { get; set; }        }        protectedvoidButton3_Click(objectsender, EventArgs e)        {            TestORM t = newTestORM()            {                Id=1,                UserName="binfire",                Password="xxx",                CreatedTime=DateTime.Now            };            Orm.OrmHelp h=newOrm.OrmHelp();            h.Insert(t);        }namespaceOrm{    [AttributeUsageAttribute(AttributeTargets.Class, Inherited = false, AllowMultiple = false)]    publicclassTableAttribute : Attribute    {        //保存表名的字段        privatestring_tableName;        publicTableAttribute()        {        }        publicTableAttribute(stringtableName)        {            this._tableName = tableName;        }        ///        /// 映射的表名(表的全名:模式名.表名)        ///        publicstringTableName        {            set            {                this._tableName = value;            }            get            {                returnthis._tableName;            }        }    }    [AttributeUsageAttribute(AttributeTargets.Property, Inherited = false, AllowMultiple = false)]    publicclassColumAttribute : Attribute    {        privatestring_columName;        privateDbType _dbType;        publicColumAttribute()        {        }        publicColumAttribute(stringcolumName)            : this()        {            this._columName = columName;        }        publicColumAttribute(stringcolumName, DbType dbType)            : this(columName)        {            this._dbType = dbType;        }        //列名        publicvirtualstringColumName        {            set            {                this._columName = value;            }            get            {                returnthis._columName;            }        }        //描述一些特殊的数据库类型        publicDbType DbType        {            get{ return_dbType; }            set{ _dbType = value; }        }    }    publicclassOrmHelp    {        publicvoidInsert(objecttable)        {            Type type = table.GetType();            //定义一个字典来存放表中字段和值的对应序列            Dictionary<string,string> columValue = newDictionary<string,string>();            StringBuilder SqlStr = newStringBuilder();            SqlStr.Append("insert into ");            //得到表名子            TableAttribute temp = (TableAttribute)type.GetCustomAttributes(typeof(TableAttribute), false).First();            SqlStr.Append(temp.TableName);            SqlStr.Append("(");            PropertyInfo[] Propertys = type.GetProperties();            foreach(varitem inPropertys)            {                object[] attributes = item.GetCustomAttributes(false);                foreach(varitem1 inattributes)                {                    //获得相应属性的值                    stringvalue = table.GetType().InvokeMember(item.Name, System.Reflection.BindingFlags.GetProperty, null, table, null).ToString();                    ColumAttribute colum = item1 asColumAttribute;                    if(colum != null)                    {                        columValue.Add(colum.ColumName, value);                    }                }            }            //拼插入操作字符串            foreach(varitem incolumValue)            {                SqlStr.Append(item.Key);                SqlStr.Append(",");            }            SqlStr.Remove(SqlStr.Length - 1, 1);            SqlStr.Append(") values(‘");            foreach(varitem incolumValue)            {                SqlStr.Append(item.Value);                SqlStr.Append("‘,‘");            }            SqlStr.Remove(SqlStr.Length - 2, 2);            SqlStr.Append(")");            HttpContext.Current.Response.Write(SqlStr.ToString());        }    }} | 
标签:
原文地址:http://www.cnblogs.com/nele/p/4805856.html