如何动态调用c#中的函数

sca*_*man 28 c#

我有方法:

  add(int x,int y)
Run Code Online (Sandbox Code Playgroud)

我也有:

int a=5;
int b=6;
string s="add";
Run Code Online (Sandbox Code Playgroud)

是否可以使用字符串s调用add(a,b)?我怎么能在c#中做到这一点?

Ric*_*ard 58

我怎么能在c#中做到这一点?

用反射.

add 必须是某种类型的成员,所以(切出很多细节):

typeof(MyType).GetMethod("add").Invoke(null, new [] {arg1, arg2})
Run Code Online (Sandbox Code Playgroud)

假设add是静态的(否则第一个参数Invoke是对象),我不需要额外的参数来唯一地标识GetMethod调用中的方法.

  • @DavidStratton 它将与`private` 成员一起使用:使用[`GetMethod`](http://msdn.microsoft.com/en-us/library/05eey4y9.aspx) 的重载之一,它需要一个[`BindingFlags` ](http://msdn.microsoft.com/en-us/library/system.reflection.bindingflags.aspx) 参数与`BindingFlags.NonPublic`。 (2认同)
  • 我们可以使用“Func<>”代替Refection吗? (2认同)

Ant*_*ony 20

使用反射 - 尝试Type.GetMethod方法

就像是

MethodInfo addMethod = this.GetType().GetMethod("add");
object result = addMethod.Invoke(this, new object[] { x, y } );
Run Code Online (Sandbox Code Playgroud)

您失去了强类型和编译时检查 - 调用不知道方法期望的参数数量,它们的类型是什么以及返回值的实际类型是什么.因此,如果你没有把它弄好的话,事情可能会在运行时失败.

它也慢了.


Amy*_*y B 14

如果函数在编译时已知,并且您只是想避免编写switch语句.

建立:

Dictionary<string, Func<int, int, int>> functions =
  new Dictionary<string, Func<int, int, int>>();

functions["add"] = this.add;
functions["subtract"] = this.subtract;
Run Code Online (Sandbox Code Playgroud)

被称为:

string functionName = "add";
int x = 1;
int y = 2;

int z = functions[functionName](x, y);
Run Code Online (Sandbox Code Playgroud)


Ita*_*aro 11

你可以使用反射.

using System;
using System.Reflection;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            Program p = new Program();
            Type t = p.GetType();
            MethodInfo mi = t.GetMethod("add", BindingFlags.NonPublic | BindingFlags.Instance);
            string result = mi.Invoke(p, new object[] {4, 5}).ToString();
            Console.WriteLine("Result = " + result);
            Console.ReadLine();
        }

        private int add(int x, int y)
        {
            return x + y;
        }
    }
}
Run Code Online (Sandbox Code Playgroud)