2007年7月26日

[.Net] Reflection for Generic Class

To dynamic create an object instance of generic type. Here's the sample code:

namespace GenericTypeNS{
public class GenericType{
......
}
}
...

Assembly asm = Assembly.LoadFrom(asmPath);
object o = asm.CreateInstance("GenericTypeNS.GenericType'1[[%TypeName%]]");

Replace %TypeName% to the specificed class name, for example if we want to create an GenericType object instance with System.Int32, it should look like this:

object o = asm.CreateInstance("GenericTypeNS.GenericType'1[[System.Int32,
mscorlib,Version=2.0.0.0,Culture=neutral,
PublicKeyToken=b77a5c561934e089]]");

沒有留言:

Blog Archive

About Me