反射的定义
反射提供了描述程序集、模块和类型的对象(Type 类型)。 可以使用反射动态创建类型的实例,将类型绑定到现有对象,或从现有对象获取类型并调用其方法或访问其字段和属性。 如果代码中使用了特性,可以利用反射来访问它们。------摘自MSDN
自我理解
看到反射二字,自然而然的会想到,小时候拿着一面镜子,反射阳光玩。其实
反射就好比一面镜子,通过它我们能在不显示引用程序集的情况下,一窥程序集内的“风景”。
利用好反射这把利器,我们在开发中就能体会到荀老夫子所言的,君子性非异也,善假于物也
本文主要包括以下四节:
通过反射调用类的构造函数(有参/无参)
通过反射调用类的静态方法(有参/无参)
通过反射调用类的非静态方法(有参/无参)
通过反射调用类的含有ref参数的方法
代码示例:
1 namespace TestDLL 2 { 3 using System.Linq; 4 5 public class TestClass 6 { 7 private int _priValue; 8 9 //无参构造函数 10 public TestClass() 11 { 12 this._priValue = 9; 13 } 14 15 //有参构造函数 16 public TestClass(int i) 17 { 18 this._priValue = i; 19 } 20 21 //无参方法 22 public int Add() 23 { 24 return ++this._priValue; 25 } 26 27 //ref参数的方法 28 public void Exchange(ref int a, ref int b) 29 { 30 int temp = b; 31 b = a; 32 a = temp; 33 } 34 35 // 静态有参方法 36 public static string SayHi(string name) 37 { 38 return "Hi~ " + name; 39 } 40 41 public static int AddValue(int[] objsInts) 42 { 43 int temp = 0; 44 if (objsInts != null) 45 { 46 temp += objsInts.Sum(); 47 } 48 return temp; 49 } 50 } 51 }