【发布时间】:2019-09-06 10:25:54
【问题描述】:
我正在搜索程序集以识别实现所需通用接口的任何类,以便我可以动态实例化实例。这是我正在使用的代码:
var types = assembly.GetTypes();
var assemblyFormatters = types.Where(type => type.GetInterfaces().Any(i =>
i.IsGenericType && i.GetGenericTypeDefinition() == typeof(IInterface<>)));
代码适用于标准类:
public class Implementation : IInterface<object>
但不适用于泛型类:
public class GenericImplementation<T> : IInterface<T>
事件陌生人,代码在中间窗口中运行时成功运行,但在单元测试框架中运行时无法运行。即时窗口返回2种类型,在调试器下运行的测试代码只返回非泛型实现。
我希望代码返回这两种类型
【问题讨论】:
-
如果代码有效,那么它就有效。问题是我猜的单元测试项目。该项目是否有正确的参考资料?
-
我是这么认为的。原来我是从
Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location)加载程序集的,它给出了相同的程序集,但由于它们的加载方式不同,程序集是不同的。我已经改用AppDomain.CurrentDomain.GetAssemblies()解决了这个问题。我将其添加为下面的答案
标签: c# reflection interface immediate-window