Reflection LateBinding
2016-01-24 17:30
197 查看
Early Binding & Late Binding
1.Early Binding 在 编译时能发现错误 ,Late Binding则有可能在运行时抛出异常
2.Early Binding 性能更好,因为Late Binding要加载程序集,创建类型,实例等
3.Use Late Binding only when working with an object that are not available at compile time.一般只对在编译时不能获取的对象采用Late Binding
通常的几个步骤:
1.Early Binding 在 编译时能发现错误 ,Late Binding则有可能在运行时抛出异常
2.Early Binding 性能更好,因为Late Binding要加载程序集,创建类型,实例等
3.Use Late Binding only when working with an object that are not available at compile time.一般只对在编译时不能获取的对象采用Late Binding
using System; using System.Reflection; namespace ReflectionLateBind { class Program { static void Main(string[] args) { //获取程序集 Assembly excutingAssembly = Assembly.GetExecutingAssembly(); //获取Type,相当于动态的创建一个class Customer Type customerType = excutingAssembly.GetType("ReflectionLateBind.Customer"); //相当于创建一个Customer的实例,但是Customer类需要能够被访问,使用Activator类 object customerInstance = Activator.CreateInstance(customerType); //创建方法 MethodInfo getFullName = customerType.GetMethod("GetFullName"); //方法参数 string[] parameters = new string[2]; parameters[0] = "James"; parameters[1] = "Bond"; //执行方法 getFullName.Invoke(object , object[] parameters) object fullName = getFullName.Invoke(customerInstance, parameters); Console.WriteLine(fullName .ToString ()); } } public class Customer { public string GetFullName(string firstName,string lastName) { return firstName + " " + lastName; } } }
通常的几个步骤:
1.获取当前程序集 //Assembly executingAssembly = Assembly.GetExecutingAssembly() 2.创建Type,对象想要在runtime中获得的类型(eg.class) // Type customerType = executingAssembly.GetType("命名空间.class名称"); 3.获取实例 返回类型为object // object customerInstance = Activator.CreateInstance(刚才创建的Type) 4.通过创建的Type来获取相应的方法,属性,构造函数等 // MethodInfo getFullName = customerType.GetMethod("对应的class名称中的方法名") //方法参数用object[],调用时传入3中的对象,getFullName(customerInstance ,parameters)
相关文章推荐
- TinyOS bug程序的执行01(T-Check中的bug)
- 【转】解决Cannot change version of project facet Dynamic web module to 2.5
- 军车车牌含义
- 把jar打包成exe
- 【转】使用VisualSVN Server搭建SVN服务器
- cocos2d-x项目101次相遇: Scenes , Director, Layers, Sprites
- [算法]字符串之变形词问题
- JavaEE Tutorials (23) - 资源适配器和契约
- BCD类型
- ISCSI Practice
- 各整形的数据范围
- 关于嵌入式软件架构的一点理解
- mysql双机热备的配置步骤
- JavaEE Tutorials (22) - 事务
- LeetCode 9:Palindrome Number
- 留训第二天
- junit(二)
- JavaEE Tutorials (21) - Java EE安全:高级主题
- Java Collections - ArrayList
- junit(一)