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
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)