简体   繁体   English

如何获取实现接口但不继承接口的类

[英]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.

相关问题 如何获取类列表,从一个类和一个接口/或者从两个接口继承 - How to get List of classes, inheriting from one class and one interface / or instead from two interfaces 使用抽象类和接口的原因? (抽象class实现接口) - Reason to use BOTH abstract classes and interfaces? (Abstract class implements interface) 如何为继承多个接口的对象创建模拟接口 - How to create a mock interface for an object inheriting multiple interfaces 接口继承多个接口:这是如何由C#编译器处理的? - interface inheriting multiple interfaces: how is this handled by a C# compiler? 获取所有首先实现接口但没有派生类的c#类型 - Get all c# Types that implements an interface first but no derived classes 对象作为没有工具的接口 - Object as Interface without implements Java“事件”-只不过是接口。 当它只是一个普通的接口和实现该接口的类时,为什么要假装它为事件? - Java “events” - nothing more than Interfaces. Why pretend it is Events when it is just a normal Interface and classes that implements that interface? 类型实现另一个接口的通用接口 - Generic interfaces which type implements another interface 如何注册实现与UnityContainer相同接口的多个类? - How to register multiple classes that implements the same interface to UnityContainer? NET CORE - AddScoped class 实现许多接口,并通过接口类型获取它们 - NET CORE - AddScoped class that implements many interfaces, and get them by interface type
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM