获取在.NET Core中实现接口的所有类型 [英] Getting all types that implement an interface in .NET Core
本文介绍了获取在.NET Core中实现接口的所有类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
使用反射,如何获得在 .NET Core 中实现某些特定接口的所有类型?我注意到,在.NET 4.6中可用的方法不再可用.
Using reflection, How can I get all types that implement some specific interface in .NET Core? I have noticed that the methods usable in .NET 4.6 are not available anymore.
例如,此代码不起作用.
For example, this code doesn't work.
var type = typeof(IMyInterface);
var types = AppDomain.CurrentDomain.GetAssemblies()
.SelectMany(s => s.GetTypes())
.Where(p => type.IsAssignableFrom(p));
它抛出名称"AppDomain"在当前上下文中不存在
错误.
推荐答案
您可以这样做:
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;
}
}
如果要在所有程序集中输入类型,只需使用以下命令即可获取所有引用,然后再次执行上述操作:)
If you want types in all assemblies, just simply use the following to get all the references and do the above again:)
ass.GetReferencedAssemblies()
这篇关于获取在.NET Core中实现接口的所有类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文