我想在运行时加载程序集,而我不能确定,为什么我不能用静态 Activator.CreateInstance()大会。它与
Assembly.CreateInstance()
。
I am trying to load an assembly at runtime, and I'm unsure as to why I can't create an instance of a type in the assembly using the static Activator.CreateInstance()
. It works with Assembly.CreateInstance()
.
string assemblyFilename = "MyAssembly.dll";
string assemblyName = "MyAssembly";
string typeName = "MyAssembly.MyType";
FileInfo fileInfo = new FileInfo(assemblyFilename);
本作品:
var assembly = Assembly.LoadFrom(assemblyFilename);
Form form = (Form)assembly.CreateInstance(typeName);
但是,这并不工作:
But this does NOT work:
Assembly.LoadFrom(assemblyFilename);
Form form = (Form)Activator.CreateInstance(assemblyName, typeName).Unwrap();
FileNotFoundException异常抛出:
FileNotFoundException thrown:
无法加载文件或程序集MyAssembly程序或它的一个 依赖性。该系统找不到指定的文件。
Could not load file or assembly 'MyAssembly' or one of its dependencies. The system cannot find the file specified.
编辑:
在这两种情况下, Assembly.LoadFrom()
通话后,我可以看到,当我在看的AppDomain我的组件已被装。 CurrentDomain.GetAssemblies()
。
In both cases, after the Assembly.LoadFrom()
call, I can see that my assembly has been loaded when I look in AppDomain.CurrentDomain.GetAssemblies()
.
您必须先加载组件到当前的AppDomain:
You have to first load the assembly into your current AppDomain:
AppDomain.CurrentDomain.Load(File.ReadAllBytes(assemblyFileName));
编辑:这是否工作
Does this work?
Form form = (Form)Activator.CreateInstance(Type.GetType(typeName))