将变量从一个类传递到另一个类

时间:2016-08-02 19:06:38

标签: c#

我目前无法将变量从一个类传递到另一个类。我的第一个类是我的表单(计算器)的默认值。第二个叫做记录。

  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()时,不会拉动变量值。这是因为创建了一个新的计算器类对象,其中变量计算为空白?任何帮助,将不胜感激。

2 个答案:

答案 0 :(得分:0)

将类的实例作为参数

传递给方法
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);
}

答案 1 :(得分:0)

修改方法StartRecording()以将计算作为参数并将计算作为参数传递

rec.startRecording(calculation);

public void startRecording(calculation_VariableType calculation) {}

不要传递hole类,只需传递类属性,因为在方法中只使用calculation属性。

相关问题