【问题标题】:C# find all class implement interface without generic typeC#查找没有泛型类型的所有类实现接口
【发布时间】:2026-02-06 08:05:03
【问题描述】:

我有InterfaceGeneric Type

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

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

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

它自己返回Interface

【问题讨论】:

    标签: c# reflection typeof


    【解决方案1】:

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

    【讨论】:

      【解决方案2】:

      您可以将 !p.IsInterface 或 p.IsClass 添加到 Where 以从结果中远程接口。

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

      【讨论】: