调用存储在字符串变量中的函数 [英] calling the function, which is stored in a string variable
问题描述
它可能是
和
由数据库值确定要调用的函数的正确性,但是以上两个有解决方案,正如答案所说的那样,不是我想的初学者。
but the above two have solutions which as the answers said are complicated, not for a beginner i guess.
和
这两种解决方案包含类型,从我认为的代码中可以定义该方法所属的类。
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,
具有函数名称 func id的数据库
a database which has "function name" "func id"
假定:-函数名称与在代码中
supposed :- function name exactly same as that in code
我只想实现以下目标
-
根据文本框中提到的ID获取函数名称的字符串值
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
methodinfo,需要输入 type.GetMethod(mymethod );
the methodinfo, needs the "type.GetMethod(mymethod);"
..
推荐答案
函数,您需要指定声明此函数的类型。如果要调用的所有函数都在公共类上声明,则可以执行以下操作:
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:
static void CallFunc(string mymethod)
{
// Get a type from the string
Type type = typeof(TypeThatContainsCommonFunctions);
// 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);
}
如果要调用的函数是静态的,则不需要类型的实例:
If the functions you are going to call are static you don't need an instance of the type:
static void CallFunc(string mymethod)
{
// Get a type from the string
Type type = typeof(TypeThatContainsCommonFunctions);
// Retrieve the method you are looking for
MethodInfo methodInfo = type.GetMethod(mymethod);
// Invoke the method on the type
methodInfo.Invoke(null, null);
}
这篇关于调用存储在字符串变量中的函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!