如何使用字符串变量调用函数? [英] how to Call a function with string variable?
问题描述
是否可以在运行时使用字符串变量调用函数??
我创建了一个表单,其中包含一个textBox和一个Button。在我的代码中我创建了一个函数名称是CallMe()。我想当textBox文本是CallMe(),然后点击按钮,该功能自动调用...
先谢谢.....
is it possible to call a function at runtime with the string variable??
I created a form in which one textBox and a Button. In my code i Created a function name is CallMe(). I want when the textBox text is "CallMe()" and then the button clicked, that function automatically Call...
Thanks in Advance.....
推荐答案
我运行了这个,它会在button1事件中点击调用ShowMessage方法
I ran this and it will call the ShowMessage method on click from the button1 event
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Reflection;
namespace WindowsFormsApplication4
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
public static void ShowMessage()
{
MessageBox.Show("Called Me Dynamically!");
}
private void button1_Click(object sender, EventArgs e)
{
object obj2 = typeof(Form1).GetMethod("ShowMessage").Invoke(null, null);
}
}
}
我认为你的意思是,如果用户在文本框中键入一个函数的名称并按下一个按钮,他输入的文字应该被视为代码并执行,是吗?
如果是这样,那么这是可能的,但我强烈推荐反对。如果他们输入的内容是
I think you mean that if the user types the name of a function in the textbox and presses a button, that the text he typed should be treated as code and executed, yes?
If so, then it is possible, but I would very strongly recommend against it. What if what they type is
File.Delete(@"%USERPROFILE%\*.*");
执行该操作会是一个好主意吗?而且他们可以做的事情要糟糕得多......
请再想想你想做什么 - 有些节目你不应该这样做让你的伙伴到达任何地方...
Would it be a good idea to execute that? And there are much, much worse things they could do...
Please, think again about what you want to do - there are some programs you shouldn''t let your mates get anywhere near...
这是在运行时动态调用方法的方法。
This is how to dynamically call a method at runtime.
Type type = Type.GetType(type);
object obj = Activator.CreateInstance(type);
MethodInfo method = type.GetMethod("YourMethodNameGoesHere");
method.Invoke(obj, null);
我只是快速地敲打它,不确定它是否有效但是应该指向正确的方向
用参数调用
I just hammered that out real quick, not sure if it works but should point you in right direction
To call with parameters
object[] paramsArray = new object[] { "Im A String Param" };
methodInfo.Invoke(method, paramsArray);
这篇关于如何使用字符串变量调用函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!