C# 如何使用按钮调用方法
我有一个简单的问题:例如,我有C# 如何使用按钮调用方法,c#,winforms,C#,Winforms,我有一个简单的问题:例如,我有 public int X(int a,int b) { } 现在,当单击按钮时,我如何调用它?我的意思是,当我单击按钮时,X()调用并工作,感谢您的帮助您需要在事件处理程序中为按钮单击进行方法调用 在VisualStudio中,如果在设计器中双击按钮,则应为您创建并连接一个空的click事件处理程序 private void Button1_Click(object sender, EventArgs e) { // Make call here
public int X(int a,int b)
{
}
现在,当单击按钮时,我如何调用它?我的意思是,当我单击按钮时,X()调用并工作,感谢您的帮助您需要在事件处理程序中为按钮单击进行方法调用 在VisualStudio中,如果在设计器中双击按钮,则应为您创建并连接一个空的click事件处理程序
private void Button1_Click(object sender, EventArgs e)
{
// Make call here
X(10, 20);
}
我建议您阅读MSDN(在Windows窗体中创建事件处理程序)。这似乎是一种实例方法。因此,第一件事是获取包含此方法的类的实例。拥有实例后,可以在其上调用方法:
var foo = new Foo();
int result = foo.X(2, 3);
如果方法声明为静态,则不再需要实例:
public static int X(int a,int b)
{
}
你可以这样调用它:
int result = Foo.X(2, 3);
或者如果这是一个类的一部分
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);
}
private void button1_Click(object sender, EventArgs e)
{
int retVal = 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 = new Foo().X(1, 2);
//or
Foo foo = new Foo();
int retVal2 = foo.X(1, 2);
}
private void button1_Click(object sender, EventArgs e)
{
int retVal = Foo.X(1, 2);
}
在按钮单击事件中调用函数 例如:
private void button1_Click(object sender, EventArgs e)
{
int value = X(5,6);
}
将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) { }
}
检查此方法声明的是什么类?在创建/单击按钮时,是否有对应调用此方法的对象的引用?应该向方法传递哪些参数?谢谢,10,20在这里起什么作用?我不能定义变量而不是10,20@arash-当然可以。这是一个例子,以说明这将如何工作@Rajesh Kumar G以
(5,6)
为例。