使用反射,如何获取在 .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/