[英]How get classes that implements interface, but without inheriting interfaces
Let's say I have interfaces IA and IB: 假设我有接口IA和IB:
public interface IA {}
public interface IB : IA {}
Now I want list of classes which implement directly IA, but without those implementing IB and others interfaces that are inherited from IA. 现在,我需要直接实现IA的类的列表,但没有那些实现IB和其他从IA继承的接口的类的列表。
If I have classes Foo and Bar: 如果我有Foo和Bar课:
public class Foo : IA {}
public class Bar : IB {}
I want my code to return only Foo class. 我希望我的代码仅返回Foo类。 I think I can do it via reflection.
我想我可以通过反思做到这一点。 I have method that returns list of all classes implementing IA, but now I don't know what to do next.
我有返回执行IA的所有类的列表的方法,但是现在我不知道下一步该怎么做。
var types = Assembly.Load("abc").GetTypes();
return types.Where(i => typeof(IA).IsAssignableFrom(i) && i.IsClass);
You could make an extension method to determine this: 您可以使用扩展方法来确定:
public static class TypeExtensions
{
public static bool DirectlyImplements(this Type testType, Type interfaceType)
{
if (!interfaceType.IsInterface || !testType.IsClass || !interfaceType.IsAssignableFrom(testType)) { return false; }
return !testType.GetInterfaces().Any(i => i != interfaceType && interfaceType.IsAssignableFrom(i));
}
}
Basically, it checks if the type implements the interface, but also checks that none of the other interfaces the class implements are assignable to it. 基本上,它检查类型是否实现了该接口,而且还检查了该类实现的其他接口均未分配给它。 It will therefore only return classes that directly implement the interface.
因此,它将仅返回直接实现该接口的类。
You can use it like this: 您可以像这样使用它:
var list = types.Where(t => t.DirectlyImplements(typeof(IA))).ToList();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.