Getting all types that implement an interface

前端 未结 17 1016
不思量自难忘°
不思量自难忘° 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:31

    Edit: I've just seen the edit to clarify that the original question was for the reduction of iterations / code and that's all well and good as an exercise, but in real-world situations you're going to want the fastest implementation, regardless of how cool the underlying LINQ looks.

    Here's my Utils method for iterating through the loaded types. It handles regular classes as well as interfaces, and the excludeSystemTypes option speeds things up hugely if you are looking for implementations in your own / third-party codebase.

    public static List GetSubclassesOf(this Type type, bool excludeSystemTypes) {
        List list = new List();
        IEnumerator enumerator = Thread.GetDomain().GetAssemblies().GetEnumerator();
        while (enumerator.MoveNext()) {
            try {
                Type[] types = ((Assembly) enumerator.Current).GetTypes();
                if (!excludeSystemTypes || (excludeSystemTypes && !((Assembly) enumerator.Current).FullName.StartsWith("System."))) {
                    IEnumerator enumerator2 = types.GetEnumerator();
                    while (enumerator2.MoveNext()) {
                        Type current = (Type) enumerator2.Current;
                        if (type.IsInterface) {
                            if (current.GetInterface(type.FullName) != null) {
                                list.Add(current);
                            }
                        } else if (current.IsSubclassOf(type)) {
                            list.Add(current);
                        }
                    }
                }
            } catch {
            }
        }
        return list;
    }
    

    It's not pretty, I'll admit.

提交回复
热议问题