Getting all types that implement an interface

前端 未结 17 1017
不思量自难忘°
不思量自难忘° 2020-11-22 00:34

Using reflection, how can I get all types that implement an interface with C# 3.0/.NET 3.5 with the least code, and minimizing iterations?

This is what I want to re-

17条回答
  •  逝去的感伤
    2020-11-22 01:13

    I got exceptions in the linq-code so I do it this way (without a complicated extension):

    private static IList loadAllImplementingTypes(Type[] interfaces)
    {
        IList implementingTypes = new List();
    
        // find all types
        foreach (var interfaceType in interfaces)
            foreach (var currentAsm in AppDomain.CurrentDomain.GetAssemblies())
                try
                {
                    foreach (var currentType in currentAsm.GetTypes())
                        if (interfaceType.IsAssignableFrom(currentType) && currentType.IsClass && !currentType.IsAbstract)
                            implementingTypes.Add(currentType);
                }
                catch { }
    
        return implementingTypes;
    }
    

提交回复
热议问题