使用反射-动态创建对象及调用对象方法
namespace ConsoleApplication1
{
public class ReflectionSample
{
private string firstName = string.Empty;
private string lastName = string.Empty;
public ReflectionSample() { }
public ReflectionSample(string firstName, string lastName)
{
this.firstName = firstName;
this.lastName = lastName;
}
public string SayHello()
{
return string.Format("Hello {0} {1}", this.firstName, this.lastName);
}
public static string StaticHello()
{
return string.Format("Hello, I am a static method");
}
}
{
public class ReflectionSample
{
private string firstName = string.Empty;
private string lastName = string.Empty;
public ReflectionSample() { }
public ReflectionSample(string firstName, string lastName)
{
this.firstName = firstName;
this.lastName = lastName;
}
public string SayHello()
{
return string.Format("Hello {0} {1}", this.firstName, this.lastName);
}
public static string StaticHello()
{
return string.Format("Hello, I am a static method");
}
}
}
创建对象,方法一:
1Assembly asm = Assembly.GetExecutingAssembly();
2Object obj = asm.CreateInstance("ConsoleApplication1.ReflectionSample", true);
2Object obj = asm.CreateInstance("ConsoleApplication1.ReflectionSample", true);
方法二:
1ObjectHandle handler = Activator.CreateInstance(null, "ConsoleApplication1.ReflectionSample");//第一个参数表示程序集名称,为null表示当前程序集
2Object obj = handler.Unwrap();
2Object obj = handler.Unwrap();
带参数构造函数的情况:
创建参数和修改createintance方法:
1//创建参数:
2Object[] paras = new Object[2];
3paras[0] = "Jimmy";
4paras[1] = "Zhang";
5
6//创建对象:
7Assembly asm = Assembly.GetExecutingAssembly();
8Object obj = asm.CreateInstance("ConsoleApplication1.ReflectionSample", true, BindingFlags.Default, null, paras, null, null);
9
10//The second way
11//ObjectHandle handler = Activator.CreateInstance(null, "ConsoleApplication1.ReflectionSample", true, BindingFlags.Default, null, paras, null, null, null);
12//Object obj = handler.Unwrap();
2Object[] paras = new Object[2];
3paras[0] = "Jimmy";
4paras[1] = "Zhang";
5
6//创建对象:
7Assembly asm = Assembly.GetExecutingAssembly();
8Object obj = asm.CreateInstance("ConsoleApplication1.ReflectionSample", true, BindingFlags.Default, null, paras, null, null);
9
10//The second way
11//ObjectHandle handler = Activator.CreateInstance(null, "ConsoleApplication1.ReflectionSample", true, BindingFlags.Default, null, paras, null, null, null);
12//Object obj = handler.Unwrap();
ss