如何在C#中动态调用方法? [英] How to dynamically call a method in C#?
本文介绍了如何在C#中动态调用方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个方法:
add(int x,int y)
我也有:
int a = 5;
int b = 6;
string s = "add";
是否可以使用字符串 s
调用 add(a,b)
?
Is it possible to call add(a,b)
using the string s
?
推荐答案
我该如何在C#中执行此操作?
how can i do this in c#?
使用反射.
add
必须是某种类型的成员,因此(省去很多细节):
add
has to be a member of some type, so (cutting out a lot of detail):
typeof(MyType).GetMethod("add").Invoke(null, new [] {arg1, arg2})
这假定 add
是静态的(否则,调用 Invoke
的第一个参数是对象),并且我不需要额外的参数即可唯一地标识中的方法GetMethod
调用.
This assumes add
is static (otherwise first argument to Invoke
is the object) and I don't need extra parameters to uniquely identify the method in the GetMethod
call.
这篇关于如何在C#中动态调用方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文