代码改变世界

通过Assembly来创建Type Instance

2012-12-29 11:58  hongjiumu  阅读(495)  评论(0编辑  收藏  举报
通过Assembly来创建Type Instance
1,
object obj=System.Reflection.Assembly.Load("assemblyname").CreateInstance("namespace.classname");
//Assembly.Load takes a assembly name, not a file path(not include the tail of ".dll")
ClassLib.User user=obj as ClassLib.User;
Result:
user is not null.

2,
object obj=System.Reflection.Assembly.LoadFile("path").CreateInstance("namespace.classname");
Attention:
ClassLib.User user=(ClassLib.User)obj;
//cannot cast.Use the LoadFile method to load and examine assemblies that have the same identity, but are located in different paths. LoadFile does not load files into the LoadFrom context, and does not resolve dependencies using the load path, as the LoadFrom method does. LoadFile is useful in this limited scenario because LoadFrom cannot be used to load assemblies that have the same identities but different paths; it will load only the first such assembly.
But 
You can do it as follows:
Type t=obj.GetType(); //t="ClassLib.User"
ClassLib.User user = (ClassLib.User)Activator.CreateInstance(t.Assembly.FullName,t.FullName).Unwrap();

3,
Type type = Assembly.LoadFile(abolutePath).GetType(typeName);
return Activator.CreateInstance(type, parameters);
这样也可以使用,可以继承着使用,或者是接口来使用。只是不能转换成ClassLib.User而已。