Finding all classes that implement C# interface - Similar to Java [duplicate]
Possible Duplicates:
Getting all types that implement an interface with C# 3.5 How to find what class(es) implements an interface (.Net)
Is this possible in C# like it is Java?
If 开发者_StackOverflow中文版I have an interface name (IDataReader for arguments sake), how do I get a list of all classes that implement this?
In java this is listed in the API - Is this available in C#
If you use ReSharper, you can right click a class or method identifier and choose "Go to Inheritor" and it will bring up a list of all the implementations of the class or method.
Visual Studio doesn't have this functionality by default though. If you don't have ReSharper, you can do it by compiling your .dll's and analyzing them in Reflector.
You can use Reflector to find the derived types of those assemblies you have loaded.
If you're talking about browsing an assembly at development time, then a static analysis tool like Reflector (as Agent_9191 suggests) is your best bet. If you're looking to do it at runtime, then reflection is the way to go. Either way, you need to define the scope of your search: what assemblies do you want to look through?
At development time, this is probably easy, and Reflector will let you easily specify these by loading the assemblies into its viewer. At runtime, this can be more difficult. To avoid greedily loading all sorts of otherwise useless assemblies, I'll assume you want to browse through all currently loaded assemblies, but this may not be correct. For this reason, I'll break this up into two functions:
public static IEnumerable<Type> GetImplementations(Type interfaceType)
{
// this will load the types for all of the currently loaded assemblies in the
// current domain.
return GetImplementations(interfaceType, AppDomain.CurrentDomain.GetAssemblies());
}
public static IEnumerable<Type> GetImplementations(Type interfaceType, IEnumerable<Assembly> assemblies)
{
return assemblies.SelectMany(
assembly => assembly.GetExportedTypes()).Where(
t => interfaceType.IsAssignableFrom(t)
);
}
Given a list of types, you can use Type.IsAssignableFrom to find the classes that implement a given interface:
IEnumerable<Type> types = Assembly.LoadFrom("assemblyPath").GetTypes();
var impls = types.Where(t => typeof(TargetInterface).IsAssignableFrom(t) && t.IsClass);
You can use reflection to look through specific assemblies and loop through all its types, to determine if its IDataReader etc. I wouldn't necessarily recommend this for most situations, and I don't believe there is anything built in.
精彩评论