web 2.0

Generic InvokeMethod Extension

Bonjour,

Une petite Extension de méthode a rajouter dans notre bonne vieille classe MyExtensions !

Le but étant de pouvoir faire appel à des méthodes par Reflection mais d'une manière plus facile.

public static T InvokeMethod<T>(this object obj, string methodName)
{
    return InvokeMethod<T>(obj, methodName, null);
}
public static T InvokeMethod<T>(this object obj, string methodName, object[] args)
{
    Type type = obj.GetType();
    MethodInfo methodInfo = type.GetMethod(methodName);
    if (methodInfo != null)
    {
        return (T)methodInfo.Invoke(obj, args);
    }
    return default(T);
}

Et l'exemple d'utilisation associé

public class Test
{
    public string lol()
    {
        return "Coucou!";
    }
    public int Calc(int a, int b)
    {
        return a + b;
    }
}
class Program
{
    static void Main(string[] args)
    {
        Test t = new Test();

        string s = t.InvokeMethod<string>("lol");
        Console.WriteLine(s);

        int result = t.InvokeMethod<int >("Calc", new object[] { 1, 2 });
        Console.WriteLine(result.ToString());
    }
}

Simple non ? :)

 

yield return this;



Views(1635)

kick it on DotNetKicks.com

Share/Save/Bookmark Subscribe

Currently rated 3.0 by 1 people

  • Currently 3/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

Tags: , ,

C#

Comments

Technorati Profile