Showing posts with label reflection. Show all posts
Showing posts with label reflection. Show all posts

Thursday, October 11, 2007

LINQ to Reflection 2

In the first reflection example, we just pulled out the types from the loaded assemblies that matched our criteria. In this example, we're searching through an array of objects and returning those that support a specific interface.


object[] objectArray = {new Queue<object>(), new StreamWriter(@"C:\temp.txt"), new List<object>()};

var supportsIEnumerable = (from obj in objectArray
from supportedInterface in obj.GetType().GetInterfaces()
where supportedInterface == typeof(IEnumerable)
select obj).ToList();


There are 2 objects in the supportsIEnumerable list.

Wednesday, October 10, 2007

LINQ to Reflection


var results = from assembly in AppDomain.CurrentDomain.GetAssemblies()
from module in assembly.GetLoadedModules()
from type in module.GetTypes()
from method in type.GetMethods()
where method.Name == "Execute"
select new
{
Assembly = assembly,
Module = module,
Type = type,
Method = method
};


This returns a set of anonymously typed objects that contain references to all of the types in all of the loaded assemblies that have an "Execute" method. If this were written in the traditional way, it would look like:

class MethodInfoContainer {
public MethodInfo Method;
public Type Type;
public Module Module;
public Assembly Assembly;
}

And the code that accomplishes what the single LINQ statement did...

List<MethodInfoContainer> results = new List<MethodInfoContainer>();

foreach(Assembly assembly in AppDomain.CurrentDomain.GetAssemblies()){
foreach ( Module module in assembly.GetLoadedModules() )
{
foreach ( Type type in module.GetTypes() )
{
foreach ( MethodInfo method in type.GetMethods() )
{
if ( method.Name == "Execute" )
{
results.Add( new MethodInfoContainer()
{
Assembly = assembly,
Module = module,
Type = type,
Method = method
} );

}
}
}
}
};