我是 C# 的新手,我只需要一些基本的东西。我试图通过单击按钮调用一个方法,但我不知道我是否在 Program.cs 或 Form1.cs 中声明了一个对象和方法
这是我到目前为止所拥有的。
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;
}
}
如果您只是从表单内部调用该方法,那么也将其设为私有,这样就无法从外部调用它。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句