c#如何在Windows窗体应用程序中使用方法?
我是c#的新手,我只需要一些基本的东西。我试图从按钮单击调用方法,我不知道我是否在Program.cs或Form1.cs中声明了一个对象和方法c#如何在Windows窗体应用程序中使用方法?
这是我迄今为止所做的。
public partial class frmMain : Form
{
Form form = new Form();
public frmMain()
{
InitializeComponent();
}
private void btnCalc_Click(object sender, EventArgs e)
{
txtC.Text = form.CalcHypotenuse(double.Parse(txtA.Text), double.Parse(txtB.Text));
}
}
public string CalcHypotenuse(double sideA, double sideB)
{
double hypotenuse = Math.Sqrt((sideA * sideA) + (sideB * sideB));
string hypotenuseString = hypotenuse.ToString();
return hypotenuseString;
}
方法需要在一个类中。你的表单是一个类,所以只需把它放在里面,然后你可以调用它。请注意我已经移动了frmMain
类中的方法并删除了线路Form form = new Form();
,因为您不需要它。
public partial class frmMain : Form
{
public frmMain()
{
InitializeComponent();
}
private void btnCalc_Click(object sender, EventArgs e)
{
// the 'this' is optional so you can remove it
txtC.Text = this.CalcHypotenuse(double.Parse(txtA.Text), double.Parse(txtB.Text));
}
public string CalcHypotenuse(double sideA, double sideB)
{
double hypotenuse = Math.Sqrt((sideA * sideA) + (sideB * sideB));
string hypotenuseString = hypotenuse.ToString();
return hypotenuseString;
}
}
如果只呼吁从表单中的唯一方法,然后将其变为私有过,因此不能从外部调用。
非常感谢你的工作。不知道我需要使用'这个' –
你不需要使用'this',我在评论中提到这一点。我总是使用它,但这是我个人的偏好。如果我已经回答了你的问题,请阅读[this](http://stackoverflow.com/help/someone-answers) – CodingYoshi
这是否为您提供了错误? – Sami
是的两个错误,“名称空间不能直接包含成员,如字段或方法”和“'表'不包含'CalcHypotenuse'的定义”“ –