C#查找没有泛型类型

时间:2018-03-26 08:19:11

标签: c# reflection typeof

InterfaceGeneric Type

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

尝试使用此代码时,我试图找到实现Classes所有通用类型的所有Interface

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

它返回Interface它自己。

2 个答案:

答案 0 :(得分:4)

问题是没有类/接口会直接扩展通用接口,它们都将扩展给定类型参数的通用接口的实例化(可以是具体类型,如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> { }

答案 1 :(得分: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);