Domanda

C'è un modo per usare Action per chiamare un metodo basato su un valore di stringa che contiene il nome di quel metodo?

È stato utile?

Soluzione

L'azione < T > è solo un tipo delegato che potrebbe puntare a un determinato metodo. Se si desidera chiamare un metodo il cui nome è noto solo in fase di runtime, memorizzato in una variabile stringa, è necessario utilizzare reflection:

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

Come suggerito da @Andrew, è possibile utilizzare Delegate.CreateDelegate per creare un tipo delegato da 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");
    }
}

Altri suggerimenti

Non credo che tu voglia davvero un Action < T > solo un metodo normale.

public void CallMethod<T>(T instance, string methodName) { 
    MethodInfo method = typeof(T).GetMethod(methodName);
    if (method != null) {
        method.Invoke(instance, null);
    }
}
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top