Created
January 18, 2014 21:04
-
-
Save Deathspike/8496429 to your computer and use it in GitHub Desktop.
simple reflection with interface and attribute c#
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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