7.7. An Advanced Interface Search Mechanism
Problem
You are searching for an interface using
the Type
class. However, complex interface
searches are not available through the
GetInterface
and
GetInterfaces
methods of a Type
object. The GetInterface
method searches for an
interface only by name (using a case-sensitive or -insensitive
search), and the GetInterfaces
method returns an
array of all the interfaces implemented on a particular type. You
want a more focused searching mechanism that might involve searching
for interfaces that define a method with a specific signature or
implemented interfaces that are loaded from the Global Assembly Cache
(GAC). You need more flexible and more advanced searching for
interfaces that does not involve creating your own interface search
engine.
Solution
The FindInterfaces
method of a Type
object can be used along with a
callback to perform complex searches of interfaces on a type. The
following method will call a custom interface searching method,
SearchInterfacesOfType
:
using System; using System.Reflection; public class SearchType { public void FindSpecificInterfaces( ) { Type[] names = new Type[3] {Type.GetType("System.ICloneable"), Type.GetType("System.Collections.ICollection"), Type.GetType("System.IAppDomainSetup")}; Type[] interfaces = SearchInterfacesOfType(Type.GetType( "System.Collections.ArrayList"), names); if (interfaces.Length > 0) { Console.WriteLine("Matches found:"); for(int counter =0; counter < interfaces.Length; counter++) ...
Get C# Cookbook now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.