Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/309.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 通过将函数名作为字符串传递来动态调用任何函数_C#_Reflection_Function_Instance - Fatal编程技术网

C# 通过将函数名作为字符串传递来动态调用任何函数

C# 通过将函数名作为字符串传递来动态调用任何函数,c#,reflection,function,instance,C#,Reflection,Function,Instance,如何自动创建实例并动态执行其功能 谢谢 编辑:也需要一个传递参数的选项。谢谢您只想调用无参数构造函数来创建实例吗?类型是否也指定为字符串,或者是否可以将其设置为泛型方法?例如: // 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

如何自动创建实例并动态执行其功能

谢谢


编辑:也需要一个传递参数的选项。谢谢

您只想调用无参数构造函数来创建实例吗?类型是否也指定为字符串,或者是否可以将其设置为泛型方法?例如:

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

public void Invoke(string methodName),其中T:new()
{
T实例=新的T();
MethodInfo method=typeof(T).GetMethod(methodName);
调用(实例,null);
}

假设要调用的方法不带任何参数:

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

我认为你的问题在这里有点过于笼统,我在这里提供了一个带有某些假设的解决方案

假设:您有一个typeName(字符串)、methodName(字符串)和一个参数(SomeType)

如果我的假设是错误的,请告诉我。

调用构造函数就可以了。它有一堆超载,让你的生活更轻松

如果您的构造函数是:

如果您需要:

若要调用,请调用一个方法,一旦拥有了对象,就可以调用以获取,然后(带参数或不带参数)调用它。如果需要,Invoke还将为您提供正在调用的函数的返回值(如果是void方法,则为null)

有关更详细的示例(粘贴到控制台应用程序中并继续):


动态传递参数 这里我采用了params string[]args,因为不同的函数有不同数量的参数

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

    }

如果没有名称空间,我们如何提供typeNameBig+1以使用InvokeMember来获得正确的方法并在一个函数中调用all-in-one呢。如果OP需要MethodInfo,我认为GetMethod也有覆盖,类似地采用参数类型来获得最佳方法。
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 });  
    } 
object instance = Activator.CreateInstance(type)
object instance =  Activator.CreateInstance(type, param1, param2)
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;
        }
    }
}
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);   

    }