Utilisation de reflection pour invoquer les méthodes

Author:

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

using System;
using System.Reflection; 

class ReflectionMéthodes
{
  int x;
  int y; 

  public ReflectionMéthodes(int i, int j) {
    x = i;
    y = j;
  }

  public int somme()
  {
      return x + y;
  }

  public bool estEntre(int i)
  {
      if (x < i && i < y) return true;
      else return false;
  }

  public void modifier(int a, int b)
  {
      x = a;
      y = b;
  }

  public void modifier(double a, double b)
  {
      x = (int)a;
      y = (int)b;
  }

  public void afficher()
  {
      Console.WriteLine(" x: {0}, y: {1}", x, y);
  }
} 

public class InvokeMethDemo {
  public static void Main() {
    Type t = typeof(ReflectionMéthodes);
    ReflectionMéthodes reflectOb = new ReflectionMéthodes(10, 20);
    int val; 

    Console.WriteLine("Invocation des méthodes de " + t.Name);
    Console.WriteLine();
    MethodInfo[] méthodes = t.GetMethods(); 

    // Invoque chaque méthode.
    foreach (MethodInfo methode in méthodes)
    {
      // Obtenir les Paramètres
      ParameterInfo[] pi = methode.GetParameters();
      //Invoquer la méthode 'modifier'
      if(methode.Name.CompareTo("modifier")==0 &&
         pi[0].ParameterType == typeof(int)) {
        object[] args = new object[2];
        args[0] = 15;
        args[1] = 65;
        methode.Invoke(reflectOb, args);
      }
      //Invoquer la méthode surchargée 'modifier'
      else if(methode.Name.CompareTo("modifier")==0 &&
         pi[0].ParameterType == typeof(double)) {
        object[] args = new object[2];
        args[0] = 12.15;
        args[1] = 23.4;
        methode.Invoke(reflectOb, args);
      }
          // invoquer la méthode 'somme'
      else if(methode.Name.CompareTo("somme")==0) {
        val = (int) methode.Invoke(reflectOb, null);
        Console.WriteLine("la somme est: " + val);
      }
      // invoquer la méthode 'estEntre'
      else if(methode.Name.CompareTo("estEntre")==0) {
        object[] args = new object[1];
        args[0] = 13;
        if((bool) methode.Invoke(reflectOb, args))
          Console.WriteLine("13 est Entre x et y");
      }
          // invocation de la méthode afficher
      else if(methode.Name.CompareTo("afficher")==0) {
        methode.Invoke(reflectOb, null);
      }
    }
  }
}

Leave a Reply

Your email address will not be published. Required fields are marked *