我有方法:
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调用中的方法.
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)