Richiamare in modo dinamico qualsiasi funzione passando il nome della funzione come stringa

StackOverflow https://stackoverflow.com/questions/801070

Domanda

Come automatizzare il processo di creazione di un'istanza e la sua funzione eseguita in modo dinamico?

Grazie

Modifica: serve anche un'opzione per passare i parametri. Grazie

È stato utile?

Soluzione

Vuoi solo chiamare un costruttore senza parametri per creare l'istanza? Anche il tipo è specificato come stringa o puoi renderlo un metodo generico? Ad esempio:

// All error checking omitted. In particular, check the results
// of Type.GetType, and make sure you call it with a fully qualified
// type name, including the assembly if it's not in mscorlib or
// the current assembly. The method has to be a public instance
// method with no parameters. (Use BindingFlags with GetMethod
// to change this.)
public void Invoke(string typeName, string methodName)
{
    Type type = Type.GetType(typeName);
    object instance = Activator.CreateInstance(type);
    MethodInfo method = type.GetMethod(methodName);
    method.Invoke(instance, null);
}

o

public void Invoke<T>(string methodName) where T : new()
{
    T instance = new T();
    MethodInfo method = typeof(T).GetMethod(methodName);
    method.Invoke(instance, null);
}

Altri suggerimenti

Per invocare un costruttore, Activator.CreateInstance farà il trucco. Ha un sacco di sovraccarichi per semplificarti la vita.

Se il costruttore è senza parametri :

object instance = Activator.CreateInstance(type)

Se hai bisogno di parametri :

object instance =  Activator.CreateInstance(type, param1, param2)

Per invocare, un metodo, una volta che hai il Tipo oggetto che puoi chiamare GetMethod per ottenere il metodo , quindi Invoke (con o senza parametri) per invocarlo. Se ne hai bisogno, Invoke ti darà anche il valore di ritorno della funzione che stai chiamando (o null se è un metodo nullo),

Per un esempio leggermente più dettagliato (incollalo in un'app console e vai):

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Reflection;

namespace Test
{
    public static class Invoker
    {
        public static object CreateAndInvoke(string typeName, object[] constructorArgs, string methodName, object[] methodArgs)
        {
            Type type = Type.GetType(typeName);
            object instance = Activator.CreateInstance(type, constructorArgs);

            MethodInfo method = type.GetMethod(methodName);
            return method.Invoke(instance, methodArgs);
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            // Default constructor, void method
            Invoker.CreateAndInvoke("Test.Tester", null, "TestMethod", null);

            // Constructor that takes a parameter
            Invoker.CreateAndInvoke("Test.Tester", new[] { "constructorParam" }, "TestMethodUsingValueFromConstructorAndArgs", new object[] { "moo", false });

            // Constructor that takes a parameter, invokes a method with a return value
            string result = (string)Invoker.CreateAndInvoke("Test.Tester", new object[] { "constructorValue" }, "GetContstructorValue", null);
            Console.WriteLine("Expect [constructorValue], got:" + result);

            Console.ReadKey(true);
        }
    }

    public class Tester
    {
        public string _testField;

        public Tester()
        {
        }

        public Tester(string arg)
        {
            _testField = arg;
        }

        public void TestMethod()
        {
            Console.WriteLine("Called TestMethod");
        }

        public void TestMethodWithArg(string arg)
        {
            Console.WriteLine("Called TestMethodWithArg: " + arg);
        }

        public void TestMethodUsingValueFromConstructorAndArgs(string arg, bool arg2)
        {
            Console.WriteLine("Called TestMethodUsingValueFromConstructorAndArg " + arg + " " + arg2 + " " + _testField);
        }

        public string GetContstructorValue()
        {
            return _testField;
        }
    }
}

Supponendo che il metodo che si desidera invocare non accetta alcun parametro:

public void InvokeMethod(Type type, string methodName)
{
    object instance = Activator.CreateInstance(type);
    MethodInfo method = type.GetMethod(methodName, BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public);

    method.Invoke(instance, null);
}

Penso che il tuo problema sia un po 'troppo generico qui, sto fornendo una soluzione con alcuni presupposti qui.

Assunzione: hai un typeName (stringa), methodName (stringa) e un parametro (di SomeType).

public static void InvokeMethod(string typeName, string methodName, SomeType objSomeType) {
      Type type = Type.GetType(typeName);
      if(type==null) {
        return;
      }
      object instance = Activator.CreateInstance(type); //Type must have a parameter-less contructor, or no contructor.   
      MethodInfo methodInfo =type.GetMethod(methodName, BindingFlags.Instance | BindingFlags.Public);
      if(methodInfo==null) {
        return;
      }
      methodInfo.Invoke(instance, new[] { objSomeType });  
    } 

fammi sapere se i miei presupposti sono sbagliati.

Per passare dinamicamente i parametri Qui ho preso params string [] args, perché funzioni diverse hanno un numero diverso di parametri così.

public void Invoke(string typeName,string functionName,params string[] args)
    {

     Type type = Type.GetType(typeName);
     dynamic c=Activator.CreateInstance(type);
     //args contains the parameters(only string type)
     type.InvokeMember(functionName,BindingFlags.InvokeMethod,null,c,args);   

    }
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top