我怎么能执行一个方法时,我有它的名字作为一个字符串 [英] How can I execute a Method when I have its name as a string

查看:95
本文介绍了我怎么能执行一个方法时,我有它的名字作为一个字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在今天接受采访(初级Web开发人员),面试官问我这个问题:

Today in an interview (junior web developer) the interviewer asked me this question:

您可以如何执行,当你有一个方法它的名字作为一个字符串(在
的JavaScript和C#)

How you can execute a Method when you have its name as a string ( in javascript and in C# )

我不能回答:(

现在http://stackoverflow.com/questions/359788/how-to-execute-a-javascript-function-when-i - 具备-其名称作为一种字符串>如何时,我有它的名字作为一个字符串

Now when I searched I found this question How to execute a JavaScript function when I have its name as a string

但如何在C#??

推荐答案

做到这一点如果你只是比你可以使用方法名的 .NET Relfection 只运行一个方法。

If you just have name of the method than you can make use of .net Relfection only to run that method..

检查:的 MethodBase.Invoke方法(对象,对象[])

例如:

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

这篇关于我怎么能执行一个方法时,我有它的名字作为一个字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆