【发布时间】:2011-08-16 11:46:45
【问题描述】:
我有两个程序集; AssemblyWithInterface 和 AssemblyWithClass。在AssemblyWithInterface 中,我有一个名为IDoSomething 的接口,它由TheClass 在AssemblyWithClass 中实现。 (AssemblyWithClass 引用 AssemblyWithInterface。)
在AssemblyWithInterface 中,我想使用反射从AssemblyWithClass 创建类的实例:
var theAssembly = Assembly.Load("Company.AssemblyWithClass, { FQN... }");
var theConcreteClass = theAssembly.CreateInstance("Company.AssemblyWithClass.TheClass");
程序集加载正常,实例创建为TheConcreteClass。
但是,我无法将 theConcreteClass 转换为它的实现接口。我在这里收到InvalidCastException:
var theConcreteClassInterfaced = (IDoSomething)theConcreteClass;
和
var isAssignable = typeof(IDoSomething).IsAssignableFrom(theConcreteClass.GetType();
是假的。
我错过了什么? (目标是具有命令模式风格的能力,可以将实现IDoSomething 的命令添加到AssemblyWithClass,并能够在AssemblyWithInterface 中执行它们,而无需更改AssemblyWithInterface 中的代码。)
平台是 .NET 3.5(不能使用动态)。
更新: 这个问题的背景(解释为什么我不遵守 DIP)是我有一个旧的 ASP.NET 应用程序包含在一个大型程序集中。我想创建一个插件程序集,它可以调用旧程序集的各个部分来执行监控和一些自动化任务。我不希望将任何其他依赖项(对其他程序集的引用)添加到旧程序集中。这个想法是在遗留程序集中实现一个钩子(一个新的特殊页面和一个IPlugInOperation),添加一个带有相应代码的监控页面。让后面的代码执行各种 IPlugInOperations(绘制一个界面以允许管理员指定用于在遗留程序集中执行代码的参数)。插件程序集必须引用遗留程序集,并且遗留程序集使用反射来列出并允许管理员执行插件程序集中包含的 IPlugInOperation 的各种实现。
【问题讨论】:
标签: c# reflection