我有一个简单的问题:例如我有
public int X(int a,int b)
{
}
现在如何在点击按钮时调用此功能?我的意思是当我点击按钮,X()通话和工作时,感谢您的帮助
答案 0 :(得分:6)
您需要在按钮单击的事件处理程序中进行方法调用。
在Visual Studio中,如果您在设计器中双击该按钮,则应创建一个空的单击事件处理程序并为您连接。
private void Button1_Click(object sender, EventArgs e)
{
// Make call here
X(10, 20);
}
我建议您阅读MSDN中的this whole topic(在Windows窗体中创建事件处理程序)。
答案 1 :(得分:3)
private void button1_Click(object sender, EventArgs e)
{
int retVal = X(1,2);
}
或者如果这是一个类的一部分
public class Foo
{
public int X(int a, int b)
{
return a + b;
}
}
然后像
private void button1_Click(object sender, EventArgs e)
{
int retVal = new Foo().X(1, 2);
//or
Foo foo = new Foo();
int retVal2 = foo.X(1, 2);
}
或者如果它是静态成员
public class Foo
{
public static int X(int a, int b)
{
return a + b;
}
}
然后像
private void button1_Click(object sender, EventArgs e)
{
int retVal = Foo.X(1, 2);
}
答案 2 :(得分:3)
在按钮点击事件中调用该函数
代表:
private void button1_Click(object sender, EventArgs e)
{
int value = X(5,6);
}
答案 3 :(得分:2)
看起来这是一个实例方法。所以首先要获取包含此方法的类的实例。一旦有了实例,就可以调用它上面的方法:
var foo = new Foo();
int result = foo.X(2, 3);
如果方法声明为static,则不再需要实例:
public static int X(int a,int b)
{
}
你可以像这样调用它:
int result = Foo.X(2, 3);
答案 4 :(得分:1)
将您的X()方法添加为按钮点击事件的委托:
public partial class Form1 : Form
{
// This method connects the event handler.
public Form1()
{
InitializeComponent();
button1.Click += new EventHandler(X);
}
// This is the event handling method.
public int X(int a,int b) { }
}