我正试图全神贯注于反射,所以我决定将插件功能添加到我正在编写的程序中。理解一个概念的唯一方法就是动手写代码,所以我创建了一个简单的接口(interface)库,其中包含 IPlugin 和 IHost 接口(interface),一个实现 IPlugin 的类的插件实现库,以及一个简单的实例化 IHost 实现类的控制台项目,该类对插件对象进行简单的工作。
使用反射,我想遍历我的插件实现 dll 中包含的类型并创建类型的实例。我能够使用此代码成功实例化类,但无法将创建的对象转换为接口(interface)。
我尝试了这段代码,但无法按预期转换对象 o。我使用调试器逐步完成了整个过程,并调用了正确的构造函数。快速观察对象 o 向我展示了它具有我希望在实现类中看到的字段和属性。
loop through assemblies
loop through types in assembly
// Filter out unwanted types
if (!type.IsClass || type.IsNotPublic || type.IsAbstract )
continue;
// This successfully created the right object
object o = Activator.CreateInstance(type);
// This threw an Invalid Cast Exception or returned null for an "as" cast
// even though the object implemented IPlugin
IPlugin i = (IPlugin) o;
我用这个编写了代码。
using System.Runtime.Remoting;
ObjectHandle oh = Activator.CreateInstance(assembly.FullName, type.FullName);
// This worked as I intended
IPlugin i = (IPlugin) oh.Unwrap();
i.DoStuff();
这是我的问题:
- Activator.CreateInstance(Type t) 返回一个对象,但我无法将该对象转换为该对象实现的接口(interface)。为什么?
- 我是否应该使用不同的 CreateInstance() 重载?
- 有哪些与反射相关的提示和技巧?
- 是否有一些重要的反射(reflection)部分是我没有得到的?
最佳答案
我只是在这里猜测,因为从你的代码中看不出你在哪里定义了 IPlugin 接口(interface),但如果你不能在你的主机应用程序中进行转换,那么你可能在你的主机程序集中有 IPlugin 接口(interface),然后在同时在您的插件程序集中。这行不通。
最简单的方法是在主机程序集中将 IPlugin 接口(interface)标记为公共(public)接口(interface),然后让插件程序集引用主机应用程序程序集,这样两个程序集都可以访问 完全相同的界面。
关于c# - 如何正确转换通过反射创建的对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31567/