Is there a way of finding what .NET classes implements a certain interface?

落花浮王杯 提交于 2019-12-05 22:37:33

To find it in MSDN, I usually go to Google, type something like "MSDN IList", and to get to IList Interface which has a section "Classes that Implement IList". That's true for any of the interface classes.

If you find a base class such as DictionaryBase, there will be a link called Derived Classes which will take you to a tree showing the inheritance hierarchy.

I think it's possible using Reflector

You can also do this programmatically.

If you know the assembly where the types are located (I'm using mscorlib as that is where string is located) you can build a list using this method:

.Net 3.0

List<Type> implementors = 
   Assembly.GetAssembly(typeof(string))
    .GetTypes()
    .Where(type => type.GetInterfaces().Contains(typeof(IList)))
    .ToList();

.Net 2.0

List<Type> implementors = new List<Type>();

foreach (Type type in Assembly.GetAssembly(typeof(string)).GetTypes())
{
    foreach (Type interfaceType in type.GetInterfaces())
    {
        if (interfaceType == typeof(IList))
        {
            implementors.Add(type);
        }
    }
}

The implementors list will hold a list of of Types that implement the interface IList. You can change IList to any interface you'd like, IDictionary, ICollection, etc.

Edit:

If you want to extend this to all assemblies in the current AppDomain, you could do:

List<Type> implementors = 
AppDomain.CurrentDomain.GetAssemblies()
.SelectMany(assembly => assembly.GetTypes()
                        .Where(type => type.GetInterfaces().Contains(typeof(IList)))
            ).ToList();

It really all depends on what you're doing with the data. If you just want to view them for your own personal satisfaction, Reflector is going to be your easiest option - especially if you want to look beyond assemblies loaded in your application domain (assuming you have an application to begin with). I suppose you could load all the assemblies from the GAC in that case... but this is basically what Reflector does except you get to pick and choose which ones you want individually.

You can lookup the interfaces a certain type implements with this method:

http://msdn.microsoft.com/en-us/library/system.type.getinterfaces.aspx

Should do the trick

Do you have a specific use case? Off the top of my head you could use:

System.Collections.ArrayList (or derived)
System.Collections.ObjectModel.Collection<T> derived
System.Collections.CollectionBase derived
System.Collections.DictionaryBase derived
System.Collections.Hashtable (or derived)
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!