Skip to main content

Use Linq and Reflection to Activate Interface and Execute a Method.

I created a simple ICommand interface similar to the one in System.Windows.Input:
[csharp]interface ICommand
{
string Description { get; }
bool CanExecute(object parameter);
void Execute();
}[/csharp]
In my project I created a bunch of classes that implement my ICommand interface and I wanted to find and execute them all.  I came up with two ways to do this, using a List<ICommand> and reflection.

List<ICommand>


This is very direct and easy but as I added new commands the list began to grow. Also I had to remember to add my commands to the list as I created them.
[csharp]
string separator = new string('=', 100);
var commandsToExec = new List<ICommand>
{
new Commands.TestEntityConnectionStringBuilderCommand(),
new Commands.BenchmarkingExampleCommand(),
new Commands.FastTokenizerBenchmarkCommand(),
new Commands.LinqToXmlTest01()
};
foreach (var cmd in commandsToExec)
if (cmd.CanExecute(null))
{
Console.WriteLine("{0}{1}{2}{1}{0}{1}", separator, Environment.NewLine, cmd.Description);
cmd.Execute();
Console.WriteLine("{1}{0}{1}{1}", separator, Environment.NewLine);
}
[/csharp]

Reflection


Using linq I find all the types in my Assembly that implements the ICommand interface.  I then loop through the results, create an instance of the object and cast it as a ICommand and then call the execute method.
[csharp]
var commandClasses = from type in Assembly.GetExecutingAssembly().GetTypes()
where type.GetInterfaces().Contains(typeof(ICommand))
select type;
foreach (var commnadType in commandClasses)
{
var cmd = Activator.CreateInstance(commnadType) as ICommand;
if (cmd.CanExecute(null))
{
Console.WriteLine("{0}{1}{2}{1}{0}{1}", separator, Environment.NewLine, cmd.Description);
cmd.Execute();
Console.WriteLine("{1}{0}{1}{1}", separator, Environment.NewLine);
}
}
[/csharp]

Comments

Popular posts from this blog

C# Spirograph Point Generators

Spirograph's  are cool.  See here and here . I put together three ways to generate points for a Spirograph, first using a Brute Force straight generate the points, second using a Parallel.For and third using LINQ.

FileSystemWatcher With the BlockingCollection

While working with the FileSystemWatcher I found that if too many files were created the built in buffer will overflowed and files will be skipped.  After much research I found out about the Producer-Consumer Problem .  Then I found that .Net 4 has the BlockingCollection which helps solve the issue.  But how to use it with the FileSystemWatcher? On StackOverflow I found  Making PLINQ and BlockingCollection work together .  I'm not so interested in the PLINQ issue but this is a great example of using The BlockingCollection with FileSystemWatcher. [csharp] using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.IO; using System.Linq; using System.Threading; namespace ConsoleApplication4 {     public class Program     {         private const string Folder = "C:\\Temp\\InputData";         static void Main(string[] args) {             var cts = new CancellationTokenSource();             foreach (var obj in Input(cts.Token))            

Remote Controlled RoboTank

This is my version of the ever popular to build RoboTank. It uses an Arduino Mega 2560 with the AdaFruit motor shield and an XBee S1 to communicate to the DFRobot Gamepad. The sketch for the RoboTank makes use of the AFMotor.h to drive the motors and includes a serial parser to read and process the commands coming from the Gamepad. Robotank-Sketch.zip DFRobot Wireless Joystick