调用该函数,该函数存储在字符串变量中
重复
和
如何实现动态调用函数,没错,要调用的函数是由数据库值决定的,使用c#,
但是上面两个的解决方案正如答案所说的很复杂,不适合我猜是初学者。
两种解决方案都
包含“类型”,从代码中我认为它是用于定义方法所属的类。
就像
static void caller(String myclass, String mymethod)
{
// Get a type from the string
Type type = Type.GetType(myclass);
// Create an instance of that type
Object obj = Activator.CreateInstance(type);
// Retrieve the method you are looking for
MethodInfo methodInfo = type.GetMethod(mymethod);
// Invoke the method on the instance we created above
methodInfo.Invoke(obj, null);
}
我最初的网站一样,只包含一个所有函数共有的类,
一个具有“函数名称”“func id”的数据库
假设:-函数名称与代码中的函数名称完全相同
我只想实现以下
根据文本框中提到的id获取函数名称的字符串值
现在调用该函数,其名称在字符串中变量
问题
中,需要“type.GetMethod(mymethod);”
..
it may be a duplicate of
How to dynamically call a class' method in .NET?
and of
but the above two have solutions which as the answers said are complicated, not for a beginner i guess.
and
both solutions contain "type" which from the code i think is for defining the class the method belongs to.
like
static void caller(String myclass, String mymethod)
{
// Get a type from the string
Type type = Type.GetType(myclass);
// Create an instance of that type
Object obj = Activator.CreateInstance(type);
// Retrieve the method you are looking for
MethodInfo methodInfo = type.GetMethod(mymethod);
// Invoke the method on the instance we created above
methodInfo.Invoke(obj, null);
}
but my initial web site, only contains one class common to all the functions,
a database which has "function name" "func id"
supposed :- function name exactly same as that in code
i only want to achieve the following
get the string value of function name according to the id mentioned in the text box
now call that function, whose name is in the string variable
problem
the methodinfo, needs the "type.GetMethod(mymethod);"
..
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
为了调用函数,您需要指定声明该函数的类型。如果您要调用的所有函数都在公共类上声明,您可以执行以下操作:
如果您要调用的函数是静态的,则不需要该类型的实例:
In order to call a function you need to specify the type this function is declared on. If all functions you are going to call are declared on a common class you could do the following:
If the functions you are going to call are static you don't need an instance of the type:
我看到 2 个解决方案:
真正的函数名
type.GetMethods() 获取所有方法的列表
方法并选择正确的一种
I see 2 solutions:
real function name
type.GetMethods() to get list of all
methods and choose right one