Question

Existe-t-il un moyen d'utiliser Action pour appeler une méthode en fonction d'une valeur de chaîne contenant le nom de cette méthode?

Était-ce utile?

La solution

L'action < T > est simplement un type de délégué pouvant pointer vers une méthode donnée. Si vous souhaitez appeler une méthode dont le nom est connu uniquement à l'exécution, stockée dans une variable chaîne, vous devez utiliser la réflexion:

class Program
{
    static void Main(string[] args)
    {
        string nameOfTheMethodToCall = "Test";
        typeof(Program).InvokeMember(
            nameOfTheMethodToCall, 
            BindingFlags.NonPublic | BindingFlags.InvokeMethod | BindingFlags.Static, 
            null, 
            null, 
            null);
    }

    static void Test()
    {
        Console.WriteLine("Hello from Test method");
    }
}

Comme suggéré par @Andrew, vous pouvez utiliser Delegate.CreateDelegate pour créer un type de délégué à partir d'un MethodInfo:

class Program
{
    static void Main(string[] args)
    {
        string nameOfTheMethodToCall = "Test";
        var mi = typeof(Program).GetMethod(nameOfTheMethodToCall, BindingFlags.NonPublic | BindingFlags.InvokeMethod | BindingFlags.Static);
        var del = (Action)Delegate.CreateDelegate(typeof(Action), mi);
        del();
    }

    static void Test()
    {
        Console.WriteLine("Hello from Test method");
    }
}

Autres conseils

Je ne pense pas que vous souhaitiez vraiment une action < T > juste une méthode régulière.

public void CallMethod<T>(T instance, string methodName) { 
    MethodInfo method = typeof(T).GetMethod(methodName);
    if (method != null) {
        method.Invoke(instance, null);
    }
}
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top