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");
}
}
}
创建对象,方法一:
Assembly asm = Assembly.GetExecutingAssembly();
Object obj = asm.CreateInstance("ConsoleApplication1.ReflectionSample", true);
方法二:
ObjectHandle handler = Activator.CreateInstance(null, "ConsoleApplication1.ReflectionSample");//第一个参数表示程序集名称,为null表示当前程序集
Object obj = handler.Unwrap();
带参数构造函数的情况:
创建参数和修改createintance方法:
//创建参数:
Object[] paras = new Object[2];
paras[0] = "Jimmy";
paras[1] = "Zhang";
//创建对象:
Assembly asm = Assembly.GetExecutingAssembly();
Object obj = asm.CreateInstance("ConsoleApplication1.ReflectionSample", true, BindingFlags.Default, null, paras, null, null);
//The second way
//ObjectHandle handler = Activator.CreateInstance(null, "ConsoleApplication1.ReflectionSample", true, BindingFlags.Default, null, paras, null, null, null);
//Object obj = handler.Unwrap();来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/12639172/viewspace-465894/ ,如需转载,请注明出处,否则将追究法律责任。