sobota, 03 august 2013 16:22 Written by 3488 times
Rate this item
(3 votes)

C# - Získanie všetkých typov implementujúcich rozhranie

Minule som pracoval na aplikácii ktorá potrebovala pluginy. Chcel som nájsť spôsob ako načítať všetky triedy, ktoré implementuju rozhranie IPlugin automaticky. Ukážeme si, aké je to jednoduche.

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();
            }

 

Last modified on pondelok, 19 december 2016 21:20
Ing.Jaroslav Vadel

Som zakladateľom www.projectik.eu.

Hrám sa na programátora, ktorý ovláda:

c#,cpp,java,unity3d,php,html,NI testand,NI Vision Builder,Cognex In-Sight,NI LabView

"Naprogramovať program, ktorý funguje vie každy. Ale to, že program funguje ešte neznamena, že je napísany správne "

Website: www.projectik.eu