当我将其名称作为字符串时,如何执行方法

今天在接受采访时(初级网络开发者),面试官问我这个问题:

如何将名称作为字符串(在javascript和C#中)执行方法

我不能回答:(

现在,当我搜索时,我发现了这个问题当我将其名称作为字符串时如何执行JavaScript函数

但是如何在c#中做到这一点?

如果您只是拥有该方法的名称,那么您只能使用.net Relfection来运行该方法。

检查: MethodBase.Invoke方法(Object,Object [])

要么

示例:

 class Class1 { public int AddNumb(int numb1, int numb2) { int ans = numb1 + numb2; return ans; } [STAThread] static void Main(string[] args) { Type type1 = typeof(Class1); //Create an instance of the type object obj = Activator.CreateInstance(type1); object[] mParam = new object[] {5, 10}; //invoke AddMethod, passing in two parameters int res = (int)type1.InvokeMember("AddNumb", BindingFlags.InvokeMethod, null, obj, mParam); Console.Write("Result: {0} \n", res); } } 

假设您有类型,可以使用reflection按名称调用方法。

 class Program { static void Main() { var car = new Car(); typeof (Car).GetMethod("Drive").Invoke(car, null); } } public class Car { public void Drive() { Console.WriteLine("Got here. Drive"); } } 

如果要调用的方法包含参数,则可以按照与方法签名相同的顺序将参数作为对象数组传递给Invoke

 var car = new Car(); typeof (Car).GetMethod("Drive").Invoke(car, new object[] { "hello", "world "}); 

好文章。 完整阅读。 您不仅可以从字符串调用方法,还可以从许多方案中调用方法。

http://www.codeproject.com/Articles/19911/Dynamically-Invoke-A-Method-Given-Strings-with-Met

如何调用其名称作为参数的共享函数