C# 单击按钮从其他类获取变量
对C#来说相当陌生,在学习一些教程时,我遇到了一个问题 如何将从一个类生成的变量传递回主窗体,以便在单击按钮时显示它 此代码模拟患者的心率:C# 单击按钮从其他类获取变量,c#,winforms,class,parameter-passing,pass-by-reference,C#,Winforms,Class,Parameter Passing,Pass By Reference,对C#来说相当陌生,在学习一些教程时,我遇到了一个问题 如何将从一个类生成的变量传递回主窗体,以便在单击按钮时显示它 此代码模拟患者的心率: class patientSim { int hr = new int(); public static genStats() { Random hr_ = new Random(); int hr = hr_.Next(40, 131); } } 此代码应
class patientSim
{
int hr = new int();
public static genStats()
{
Random hr_ = new Random();
int hr = hr_.Next(40, 131);
}
}
此代码应在单击按钮时显示心率hr
public partial class mainForm : Form
{
public static void simBtn_Click(object sender, EventArgs e)
{
patientSim.genStats();
MessageBox.Show = hr;
}
}
我确信它非常简单,但我能完全理解它。您的方法需要一个返回值:
public static int genStats()
{
Random hr_ = new Random();
int hr = hr_.Next(40, 131);
return hr;
}
然后使用:
public static void simBtn_Click(object sender, EventArgs e)
{
int hr = patientSim.genStats();
MessageBox.Show(hr);
}
请记住,您必须在方法上声明一个返回值。如果您不想返回任何内容,可以使用
void
类patientsSim
(按照惯例,该类应被写入PatientSim并将hr
定义为私有字段。您需要修改该类才能访问它。一种可能的修改是向PatientSim添加一个返回hr
值的getter:
public int Hr { get { return hr; } }
然后以你的形式
patientSim.genStats();
MessageBox.Show("HR: " + patientSim.Hr);
不过,您还有一些其他问题:
int hr = hr_.Next(40, 131);
隐藏类级别变量hr
。因此将其更改为
hr = hr_.Next(40, 131);
然后,您的类的实例部分和静态范围部分不匹配。您可以将类级别hr
与建议的getter一起更改为静态,或者将事件处理程序更改为非静态