V prvom kroku si vytvoríme nejaké rozhranie (interface). Nazveme ho napr IPlugin.
Kód v c#:
public interface IPlugin { string Name { get; } void Execute(); }
V ďalšom kroku vytvoríme triedy (class) Plugin1 a Plugin2, ktoré budu implementovať rozhranie IPlugin.
Kód v c#:
public class Plugin1:IPlugin { string Name { get { return "Plugin1"; } } void Execute() { MessageBox.Show("som plugin 1"); } } public class Plugin2 : IPlugin { string Name { get { return "Plugin2"; } } void Execute() { MessageBox.Show("som plugin 2"); } }
V ďalšom kroku vytvoríme staticku metódu GetAllClassWithInterface<T>(), ktorá nám získa vsetky types v assembly. Následne pomocou LINQ vyberieme vsetky typy s rozhraním T okrem samotného rozhrania.
Kód v c#:
public static IEnumerable<Type> GetAllClassWithInterface<T>() { Assembly asm = Assembly.GetExecutingAssembly(); Type[] types = asm.GetTypes(); return types.Where(x => typeof(T).IsAssignableFrom(x) && !x.IsInterface); }
Metódu GetAllClassWithInterface použijeme na ziskanie vsetkych triedy s rozhranim IPlugin. Následne vytvoríme instanciu triedy a spustime metódu Execute();
Kód v c#:
var result = GetAllClassWithInterface<IPlugin>(); foreach (Type t in result) { IPlugin myPlugin = (IPlugin)Activator.CreateInstance(t); myPlugin.Execute(); }