Dinamicamente chamar qualquer função, passando o nome da função como uma string
-
03-07-2019 - |
Pergunta
Como faço para automatizar o processo de obtenção de uma instância criada e sua função executada dinamicamente?
Graças
Edit: Precisa de uma opção para passar parâmetros também. Graças
Solução
Você só quer chamar um construtor sem parâmetros para criar a instância? É o tipo especificado como uma string, bem como, ou você pode torná-lo um método genérico? Por exemplo:
// 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);
}
ou
public void Invoke<T>(string methodName) where T : new()
{
T instance = new T();
MethodInfo method = typeof(T).GetMethod(methodName);
method.Invoke(instance, null);
}
Outras dicas
Para chamar um construtor, Activator.CreateInstance irá fazer o truque. Ele tem um monte de sobrecargas para tornar a sua vida mais fácil.
Se o seu construtor é parâmetros :
object instance = Activator.CreateInstance(type)
Se você precisa parâmetros :
object instance = Activator.CreateInstance(type, param1, param2)
Para chamar, um método, uma vez que você tem a Tipo objeto que você pode chamar GetMethod
para obter o método , e, em seguida, Invoke
(com ou sem parâmetros) para invocá-lo. Se você precisar dele, Invoke também lhe dará o valor de retorno da função que você está chamando (ou nulo se o seu método void),
Para uma amostra um pouco mais detalhada (colar em um aplicativo de console e ir):
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;
}
}
}
Assumindo que o método que você deseja chamar não tomar quaisquer parâmetros:
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);
}
Eu acho que o problema é pouco demasiado genérico aqui, eu estou fornecendo uma solução com certas suposições aqui.
Assunção: você tem um typeName (string), methodName (string), e um parâmetro (de 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 });
}
deixe-me saber saber se minhas suposições estão erradas.
Para passar os parâmetros dinamicamente Aqui eu ter tomado corda params [] args, porque diferentes funções têm número diferente de parâmetros lo.
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);
}