[英]Passing variable from one class to another
我目前无法将变量从一类传递到另一类。 我的第一堂课是由我的名为(Calculator)的表单制作的默认班级。 第二个称为记录。
public void toolStripLabel1_Click(object sender, EventArgs e)
{
Record rec = new Record();
System.Windows.Forms.MessageBox.Show(calculation);
rec.startRecording();
}
当我单击正确的变量时,以上内容将显示在弹出框中。
namespace CalculatorV2
{
class Record
{
public void startRecording()
{
Calculator calc = new Calculator();
System.Windows.Forms.MessageBox.Show(calc.calculation);
using (StreamWriter writer =
new StreamWriter("important.txt"))
{
writer.WriteLine("Line one");
writer.WriteLine(calc.calculation);
writer.WriteLine("Line Two");
}
}
}
}
但是当我调用方法startRecording()时,变量值没有被提取。 这是因为创建了一个新的计算器类对象,其中变量计算为空白吗? 任何帮助,将不胜感激。
将类的实例作为参数传递给方法
class Record
{
public void startRecording(Calculator calculator)
{
System.Windows.Forms.MessageBox.Show(calculator.calculation);
using (StreamWriter writer =
new StreamWriter("important.txt"))
{
writer.WriteLine("Line one");
writer.WriteLine(calculator.calculation);
writer.WriteLine("Line Two");
}
}
}
public void toolStripLabel1_Click(object sender, EventArgs e)
{
Record rec = new Record();
System.Windows.Forms.MessageBox.Show(calculation);
rec.startRecording(this);
}
修改您的方法StartRecording()以将计算作为参数并将计算作为参数传递
rec.startRecording(calculation);
public void startRecording(calculation_VariableType calculation) {}
无需传递孔类,只需传递class属性即可,因为您仅在方法中使用calculation
属性。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.