C#查找所有实现接口但没有泛型类型的类

4

我有一个带有通用类型接口

public interface IWork<T>
{
    void Work(MySession session, T json);
}

我正在尝试查找所有实现具有所有泛型类型的接口,当尝试运行以下代码时:

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

它返回 Interface 本身。

2个回答

8
问题在于没有任何类/接口会直接扩展泛型接口,它们都会为给定类型参数的泛型接口实例化(无论是像string这样的具体类型还是另一个类型参数)。您需要检查类实现的任何接口是否为泛型接口的实例:
class Program
{
    static void Main(string[] args)

    {
        var type = typeof(IWork<>);
        var types = AppDomain.CurrentDomain.GetAssemblies()
                    .SelectMany(s => s.GetTypes())
                    .Where(p => p.GetInterfaces().Any(i=> i.IsGenericType && i.GetGenericTypeDefinition() == type))
                    .ToArray();

        // types will contain GenericClass, Cls2,Cls,DerivedInterface  defined below
    }
}

public interface IWork<T>
{
    void Work(object session, T json);
}

class GenericClass<T> : IWork<T>
{
    public void Work(object session, T json)
    {
        throw new NotImplementedException();
    }
}
class Cls2 : IWork<string>
{
    public void Work(object session, string json)
    {
        throw new NotImplementedException();
    }
}
class Cls : GenericClass<string> { }

interface DerivedInterface : IWork<string> { }

0

您可以在 Where 子句中添加 !p.IsInterface 或 p.IsClass 条件来从结果中排除接口。

var type = typeof(IWork<>);
var types = AppDomain.CurrentDomain.GetAssemblies()
            .SelectMany(s => s.GetTypes())
            .Where(p => type.IsAssignableFrom(p) && !p.IsInterface);

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接