如何从库中初始化一个类?
我在类库中有一些类(单独的程序集)。我将其引用到我的项目中,并且我想从该库中初始化一个特定的类。我只知道它的名字。所有类都实现一个接口。 问题来了。
到目前为止我的代码:
using MyLibrary;
...
IMyInterface dll = Activator.CreateInstance("MyLibrary", "MyLibrary.NameOfClass") as IMyInterface;
但是 dll 始终为空。 有什么想法吗?
谢谢
更新,
我删除了对库的引用并将该代码重写为:
Assembly a = Assembly.Load("MyLibrary");
Type type = a.GetType("MyLibrary.SKClass");
IMyInterface obj = Activator.CreateInstance(type) as IMyInterface;
但 obj 为空。
如果我使用 a.GetExportedTypes() 检查库类型,就会发现 SKClass 就在那里。那么为什么这段代码仍然返回 null 呢?
I have a few classes in the class library (separate assembly). I referenced it to my project and I want to initialize one specific class from that library. I know only its name. All of the classes implements one interface.
And here comes the problem.
My code so far:
using MyLibrary;
...
IMyInterface dll = Activator.CreateInstance("MyLibrary", "MyLibrary.NameOfClass") as IMyInterface;
But dll is always null.
Any ideas?
Thanks
UPDATE
I remove reference to the library and rewrite that code to:
Assembly a = Assembly.Load("MyLibrary");
Type type = a.GetType("MyLibrary.SKClass");
IMyInterface obj = Activator.CreateInstance(type) as IMyInterface;
but obj is null.
If I checked library types with a.GetExportedTypes(), SKClass is there. So why is this code still returning null?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
你为什么不使用这个...?
程序集 a = Assembly.Load("ClassLibrary1");
Interface1 i = a.CreateInstance("ClassLibrary1.ClassName") as Interface1;
有必要使用Activator吗...?
Why aren't you using this...?
Assembly a = Assembly.Load("ClassLibrary1");
Interface1 i = a.CreateInstance("ClassLibrary1.ClassName") as Interface1;
Is it necessary that you have to use Activator...?