c# - 获取在 .NET Core 中实现接口(interface)的所有类型

标签 c# .net reflection lambda .net-core

使用反射,如何获取在 .NET Core 中实现某些特定接口(interface)的所有类型?我注意到 .NET 4.6 中可用的方法不再可用。

例如,这段代码不起作用。

var type = typeof(IMyInterface);
var types = AppDomain.CurrentDomain.GetAssemblies()
    .SelectMany(s => s.GetTypes())
    .Where(p => type.IsAssignableFrom(p));

它抛出 The name 'AppDomain' does not exist in the current context 错误。

最佳答案

你可以这样做:

System.Reflection.Assembly ass = System.Reflection.Assembly.GetEntryAssembly();

foreach (System.Reflection.TypeInfo ti in ass.DefinedTypes)
{
    if (ti.ImplementedInterfaces.Contains(typeof(yourInterface)))
    {
        ass.CreateInstance(ti.FullName) as yourInterface;
    }  
}

如果您想要所有程序集中的类型,只需简单地使用以下获取所有引用并再次执行上述操作:)

ass.GetReferencedAssemblies()

关于c# - 获取在 .NET Core 中实现接口(interface)的所有类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38443347/

相关文章:

c# - WPF 组合框所选项目错误 - 显示 "System.Data.Entity.DynamicProxies"

iPhone:使用反射替换函数

c# - 通过反射找不到添加到程序集中的新类

c# - 如何获得进程所有者的用户名?

c# - 如何将 WCF 客户端代理生成的类中的方法标记为虚拟

c# - 为什么使用 System.Data.Entity 只需要引用 Entity Framework ?

c# - 使用主机作为 IP 地址的 SMTP 发送邮件时无法解析远程名称

c# - 结合代码契约(Contract)和正则表达式

java - 传递方法作为参数并收到错误 : java. lang.NoSuchMethodException:

C# WPF 属性网格文件浏览器