今天,面试官在一次面试(初级网络开发者)中问我这个问题:
当方法名为字符串时(在javascript和C#中),如何执行该方法
我无法回答:
当我搜索的时候,我发现了当JavaScript函数的名称为字符串时,如何执行它这个问题
,但是c# ??是怎么做到的呢?
发布于 2012-05-14 06:01:36
如果您只知道该方法的名称,则只能使用.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);
}
}
发布于 2012-05-14 06:04:40
假设您有该类型,则可以使用反射按其名称调用方法。
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 "});
发布于 2012-05-14 06:06:05
好文章。好好读一读。不仅可以从字符串调用方法,还可以从许多场景调用方法。
http://www.codeproject.com/Articles/19911/Dynamically-Invoke-A-Method-Given-Strings-with-Met
https://stackoverflow.com/questions/10578074
复制相似问题