{
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");
}
}
}
创建对象,方法一:
1
Assembly asm
=
Assembly.GetExecutingAssembly();
2 Object obj = asm.CreateInstance( " ConsoleApplication1.ReflectionSample " , true );
2 Object obj = asm.CreateInstance( " ConsoleApplication1.ReflectionSample " , true );
方法二:
1
ObjectHandle handler
=
Activator.CreateInstance(
null
,
"
ConsoleApplication1.ReflectionSample
"
);
//
第一个参数表示程序集名称,为null表示当前程序集
2 Object obj = handler.Unwrap();
2 Object obj = handler.Unwrap();
带参数构造函数的情况:
创建参数和修改createintance方法:
1
//
创建参数:
2 Object[] paras = new Object[ 2 ];
3 paras[ 0 ] = " Jimmy " ;
4 paras[ 1 ] = " Zhang " ;
5
6 // 创建对象:
7 Assembly asm = Assembly.GetExecutingAssembly();
8 Object 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();
2 Object[] paras = new Object[ 2 ];
3 paras[ 0 ] = " Jimmy " ;
4 paras[ 1 ] = " Zhang " ;
5
6 // 创建对象:
7 Assembly asm = Assembly.GetExecutingAssembly();
8 Object 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