Skip to content

Instantly share code, notes, and snippets.

@Deathspike
Created January 18, 2014 21:04
Show Gist options
  • Select an option

  • Save Deathspike/8496429 to your computer and use it in GitHub Desktop.

Select an option

Save Deathspike/8496429 to your computer and use it in GitHub Desktop.
simple reflection with interface and attribute c#
using System;
using System.Linq;
using System.Reflection;
namespace reflectos {
// interface to implement a command
interface ICommand {
void Run();
}
// attribute to mark implementations with and add meta-data
class CommandAttribute : Attribute {
public CommandAttribute(string name) {
Name = name;
}
public string Name { get; private set; }
public string HelpText { get; set; }
}
// los examplos
[CommandAttribute("example", HelpText = "Epic help.")]
class Example : ICommand {
public void Run() {
Console.WriteLine("Los epicnoss.");
}
}
// los loados example
class Program {
static void Main(string[] args) {
var thisAssembly = Assembly.GetExecutingAssembly();
var commands = thisAssembly.GetTypes()
.Where(x => x.GetInterface(typeof(ICommand).FullName) != null)
.Where(x => x.GetCustomAttribute(typeof(CommandAttribute)) != null)
.ToDictionary(x=>((CommandAttribute)x.GetCustomAttribute(typeof(CommandAttribute))).Name, x => Activator.CreateInstance(x) as ICommand);
commands["example"].Run();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment