一:反射的定义

  审查元数据并收集关于它的类型信息的能力。元数据(编译以后的最基本数据单元)就是一大堆的表,当编译程序集或者模块时,编译器会创建一个类定义表,一个字段定义表,和一个方法定义表等。

  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 }

三:获取程序集信息

protected void Button2_Click(object sender, 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 (var item in types)
    {
        Response.Write("<br/>");
        Response.Write("类:"+item.Name);
    }
}<br>

 四:反射调用方法

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
protected void Page_Load(object sender, EventArgs e)
 {  
     System.Reflection.Assembly ass = Assembly.LoadFrom(AppDomain.CurrentDomain.BaseDirectory+"bin\\WebApplication1.dll"); //加载DLL
     System.Type t = ass.GetType("WebApplication1.MainPage");//获得类型
 
       string name=typeof(MainPage).AssemblyQualifiedName;
     System.Type t1 = Type.GetType(name);
System.Type t2 = typeof(MainPage);
 
     object o = System.Activator.CreateInstance(t);//创建实例
       System.Reflection.MethodInfo mi = t.GetMethod("RunJs1");//获得方法
       mi.Invoke(o, new object[] { this.Page, "alert('测试反射机制')" });//调用方法
 
       System.Reflection.MethodInfo mi1 = t.GetMethod("RunJs");
     mi1.Invoke(t, new object[] { 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
       protected override void OnInit(EventArgs e)
        {  
            //生成控件
              CreateControl();
            base.OnInit(e);
        }
 
        private void CreateControl()
        {
            Table tb = new Table();
            TableRow dr = new TableRow();
            TableCell cell = new TableCell();
            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);
        }
 
        protected void Button1_Click(object sender, EventArgs e)
        {
            foreach (TableRow tr in PlaceHolder1.Controls[0].Controls)
            {
                foreach (TableCell tc in tr.Controls)
                {
                    foreach (Control ctl in tc.Controls)
                    {
                        if (ctl is UserControl)
                        {
                            Type type = ctl.GetType();
                            System.Reflection.MethodInfo methodInfo = type.GetMethod("GetResult");
                            string selectedValue = string.Concat(methodInfo.Invoke(ctl, new object[] { }));
 
                            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
public partial class 反射 : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            string typeName = typeof(TestClass).AssemblyQualifiedName;
            ITestInterface iface = RawGenericFactory.Create<ITestInterface>(typeName);
            string result = iface.doSomething();
            Response.Write(result);
        }
    }
 
    public static class RawGenericFactory
    {
        public static T Create<T>(string typeName)
        {
            //Activator.CreateInstance 反射 根据程序集创建借口或者类
            //Type.GetType() 根据名称获得程序集信息
            //typeof(ConcertProduct).AssemblyQualifiedName
            //_iproduct.GetType().AssemblyQualifiedName
            return (T)Activator.CreateInstance(Type.GetType(typeName));
        }
    }
 
    public interface ITestInterface
    {
        string doSomething();
    }
 
    public class TestClass : ITestInterface
    {
        public int Id { getset; }
        public override string ToString()
        {
            return Id.ToString();
        }
 
        public string doSomething()
        {
            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")]
        public class TestORM
        {  
            [Orm.Colum("Id",DbType.Int32)]
            public int Id { getset; }
            [Orm.Colum("UserName", DbType.String)]
            public string UserName { getset; }
            [Orm.Colum("Password", DbType.String)]
            public string Password { getset; }
            [Orm.Colum("CreatedTime", DbType.DateTime)]
            public DateTime CreatedTime { getset; }
        }
 
 
        protected void Button3_Click(object sender, EventArgs e)
        {
            TestORM t = new TestORM()
            {
                Id=1,
                UserName="binfire",
                Password="xxx",
                CreatedTime=DateTime.Now
            };
            Orm.OrmHelp h=new Orm.OrmHelp();
            h.Insert(t);
        }
 
namespace Orm
{
    [AttributeUsageAttribute(AttributeTargets.Class, Inherited = false, AllowMultiple = false)]
    public class TableAttribute : Attribute
    {
        //保存表名的字段
        private string _tableName;
 
        public TableAttribute()
        {
        }
 
        public TableAttribute(string tableName)
        {
            this._tableName = tableName;
        }
 
        ///
 
        /// 映射的表名(表的全名:模式名.表名)
        ///
        public string TableName
        {
            set
            {
                this._tableName = value;
            }
            get
            {
                return this._tableName;
            }
        }
    }
 
    [AttributeUsageAttribute(AttributeTargets.Property, Inherited = false, AllowMultiple = false)]
    public class ColumAttribute : Attribute
    {
        private string _columName;
 
        private DbType _dbType;
 
 
        public ColumAttribute()
        {
        }
 
        public ColumAttribute(string columName)
            this()
        {
            this._columName = columName;
        }
 
        public ColumAttribute(string columName, DbType dbType)
            this(columName)
        {
            this._dbType = dbType;
        }
 
        //列名
        public virtual string ColumName
        {
            set
            {
                this._columName = value;
            }
            get
            {
                return this._columName;
            }
        }
 
        //描述一些特殊的数据库类型
        public DbType DbType
        {
            get return _dbType; }
            set { _dbType = value; }
        }
 
    }
 
    public class OrmHelp
    {
        public void Insert(object table)
        {
            Type type = table.GetType();
            //定义一个字典来存放表中字段和值的对应序列
            Dictionary<string,string> columValue = new Dictionary<string,string>();
            StringBuilder SqlStr = new StringBuilder();
            SqlStr.Append("insert into ");
            //得到表名子
            TableAttribute temp = (TableAttribute)type.GetCustomAttributes(typeof(TableAttribute), false).First();
            SqlStr.Append(temp.TableName);
            SqlStr.Append("(");
            PropertyInfo[] Propertys = type.GetProperties();
            foreach (var item in Propertys)
            {
                object[] attributes = item.GetCustomAttributes(false);
                foreach (var item1 in attributes)
                {
                    //获得相应属性的值
                    string value = table.GetType().InvokeMember(item.Name, System.Reflection.BindingFlags.GetProperty, null, table, null).ToString();
                    ColumAttribute colum = item1 as ColumAttribute;
                    if (colum != null)
                    {
                        columValue.Add(colum.ColumName, value);
                    }
                }
            }
            //拼插入操作字符串
            foreach (var item in columValue)
            {
                SqlStr.Append(item.Key);
                SqlStr.Append(",");
 
            }
            SqlStr.Remove(SqlStr.Length - 1, 1);
            SqlStr.Append(") values('");
            foreach (var item in columValue)
            {
                SqlStr.Append(item.Value);
                SqlStr.Append("','");
 
 
            }
            SqlStr.Remove(SqlStr.Length - 2, 2);
            SqlStr.Append(")");
 
            HttpContext.Current.Response.Write(SqlStr.ToString());
 
        }
    }
}

c#反射机制的更多相关文章

  1. Java学习之反射机制及应用场景

    前言: 最近公司正在进行业务组件化进程,其中的路由实现用到了Java的反射机制,既然用到了就想着好好学习总结一下,其实无论是之前的EventBus 2.x版本还是Retrofit.早期的View注解框 ...

  2. 第28章 java反射机制

    java反射机制 1.类加载机制 1.1.jvm和类 运行Java程序:java 带有main方法的类名 之后java会启动jvm,并加载字节码(字节码就是一个类在内存空间的状态) 当调用java命令 ...

  3. NPOI操作EXCEL(四)——反射机制批量导出excel文件

    前面我们已经实现了反射机制进行excel表格数据的解析,既然有上传就得有下载,我们再来写一个通用的导出方法,利用反射机制实现对系统所有数据列表的筛选结果导出excel功能. 我们来构想一下这样一个画面 ...

  4. Java反射机制

    Java反射机制 一:什么事反射机制 简单地说,就是程序运行时能够通过反射的到类的所有信息,只需要获得类名,方法名,属性名. 二:为什么要用反射:     静态编译:在编译时确定类型,绑定对象,即通过 ...

  5. java基础知识(十一)java反射机制(上)

    java.lang.Class类详解 java Class类详解 一.class类 Class类是java语言定义的特定类的实现,在java中每个类都有一个相应的Class对象,以便java程序运行时 ...

  6. java基础知识(十一)java反射机制(下)

    1.什么是反射机制? java反射机制是在运行状态中,对于任意一个类,都能够知道这个类的所有属性和方法,对于任意一个对象都能够调用他的属性和方法,这种动态获取属性和方法的功能称为java的反射机制. ...

  7. java反射学习之一反射机制概述

    一.反射机制背景概述 1.反射(reflection)是java被视为动态语言的一个关键性质 2.反射机制指的是程序在运行时能获取任何类的内部所有信息 二.反射机制实现功能概述 1.只要给定类的全名, ...

  8. Java中的反射机制

    Java反射机制 反射机制定义 反射机制是Java语言中一个非常重要的特性,它允许程序在运行时进行自我检查,同时也允许其对内部成员进行操作.由于反射机制能够实现在运行时对类进行装载,因此能够增加程序的 ...

  9. C#反射机制 (转载)

    转载:原文出处      http://www.cnblogs.com/binfire/archive/2013/01/17/2864887.html 一:反射的定义 审查元数据并收集关于它的类型信息 ...

随机推荐

  1. 【Mutual Training for Wannafly Union #1 】

    A.Phillip and Trains CodeForces 586D 题意:过隧道,每次人可以先向前一格,然后向上或向下或不动,然后车都向左2格.问能否到达隧道终点. 题解:dp,一开始s所在列如 ...

  2. 思维导图FreeMind安装问题及简单使用

    思维导图软件使用的坎坷之路 一直想将思维导图加入到工作环境当中 最开始使用的是 MindManager(http://www.mindmanager.cc/) ,而且感觉利用它制作出来的导图外观也比较 ...

  3. C#面向对象设计模式纵横谈——1.面向对象设计模式与原则

    一:设计模式简介 每一个模式描述了一个在我们周围不断重复发生的问题,以及该问题的解决方案的核心. ---- Christopher Alexander 软件设计领域设计模式: 设计模式描述了软件设计过 ...

  4. 关于input的file框onchange事件触发一次失效的新的解决方法

    在google了众多方法后,网上有这么几种方法: 1.替换掉原来的input框 2.remove原来的input框,然后在添加进新的一样的input框 但是不知道为什么非常不幸的是,怎么弄我都弄不出. ...

  5. BZOJ 4390: [Usaco2015 dec]Max Flow

    4390: [Usaco2015 dec]Max Flow Time Limit: 10 Sec  Memory Limit: 128 MBSubmit: 177  Solved: 113[Submi ...

  6. [Android] Visual Studio Emulator For Android 相关

    1.修改设备名 C:\Users\[用户名]\AppData\Local\Microsoft\VisualStudioEmulator\Android\Containers\Local\Devices ...

  7. 批量 ping 测试脚本

    是否会使用 vpn 工作,已经成为魔法师和麻瓜之间最重要的区分.使用 vpn 工作,也产生了其它一些奇奇怪怪的问题,比如,选择 vpn 服务器. 你要测试哪个 vpn 离你最近. 所以,就有了下面的脚 ...

  8. Java开发环境搭建——CentOS配置

    普通用户添加到sudoers u切换到root visudo进入编辑,找到root  ALL=(ALL)    ALL,在后面加上myusername ALL=(ALL)  ALL 配置网络sudo ...

  9. skipping the actual organic impact moderation supplied

    The most recent running footwear design has gone out. The high cost is actually $150. Expert sports ...

  10. Jmeter响应内容为文件

    最近测试一个接口是文档转换的接口,比如说把rtf文件转换为PDF,这样的接口调用通过结果树只能查看接口响应是否成功,但是看不到转换后的文档.通过Jmeter监听中的Save Responses to  ...