Digg StumbleUpon LinkedIn YouTube Flickr Facebook Twitter RSS Reset

Invocation Dynamique des méthodes

Charger,une,Assemblée,avec,un,nom
{filelink=17579}

using System;
using System.Reflection;
 
namespace Ref
{
    interface IMyInterface
    {
        void AfficherUnString(string s);
        void AfficherUnInteger(int i);
        void AffichageDivers(string desc, int i, double d);
        int obtenirDonnée(string s);
    }
 
    public class MaClasse : IMyInterface
    {
        public MaClasse()
        {
        }
        public void AfficherUnString(string s)
        {
            Console.WriteLine("AfficherUnString: {0}", s);
        }
        public void AfficherUnInteger(int i)
        {
            Console.WriteLine("AfficherUnInteger: {0}", i);
        }
        public void AffichageDivers(string desc, int i, double d)
        {
            Console.WriteLine("AffichageDivers: {0}", desc);
            Console.WriteLine("Integer: {0}", i);
            Console.WriteLine("Double: {0}", d);
        }
        public int obtenirDonnée(string s)
        {
            Console.WriteLine("obtenirDonnéee: {0}", s);
            return 125;
        }
        public int operation(string s, int i, double d)
        {
            IMyInterface mi = (IMyInterface)this;
            mi.AffichageDivers(s, i, d);
            return mi.obtenirDonnée(s);
        }
    }
 
    public class MainClass
    {
        public static void InvocationDynamique(string assembly)
        {
            Assembly ass = Assembly.LoadFrom(assembly);
            foreach (Type t in ass.GetTypes())
            {
                if (t.IsClass == false)
                    continue;
                if (t.GetInterface("IMyInterface") == null)
                    continue;
                Console.WriteLine("Création d'une instance de {0}", t.FullName);
                object obj = Activator.CreateInstance(t);
                object[] args = { "Dynamique", 1, 125.4 };
                object result;
                result = t.InvokeMember("operation", BindingFlags.Default | BindingFlags.InvokeMethod, null, obj, args);
                Console.WriteLine("Resultat de l'appel dynamique: {0}", result);
                object[] args2 = { 12 };
                t.InvokeMember("AfficherUnInteger", BindingFlags.Default | BindingFlags.InvokeMethod, null, obj, args2);
            }
        }
        public static void Main(string[] args)
        {
            MaClasse dmi = new MaClasse();
            dmi.AffichageDivers("Affichage", 1, 3.9);
            int i = dmi.obtenirDonnée("Bye");
            Console.WriteLine("I = {0}", i);
            InvocationDynamique(args[0]);
        }
    }
 
}

No comments yet.

Leave a Comment