0

我有一个系统计时器每 10 秒触发一次事件。所以每 10 秒我从表单的主线程调用类“Termocoppia”,将“milliV”的值传递给它,并期望取回变量“tempEx”的值。

public partial class Form1 : Form
{

        public Form1()
        {
        InitializeComponent();
        System.Windows.Forms.Timer timer = new System.Windows.Forms.Timer();
        timer.Tick += OnTimerTick;
        timer.Interval = 10000;
        timer.Start();
}

double tempEx;

//here a call the method "Calcola" in the class "Termocoppia"
private void OnTimerTick(object sender, EventArgs e)
{
        double milliV = Convert.ToDouble(textBox8.Text); //I have a value of 1.111
        Termocoppia thm = new Termocoppia();
        thm.Calcola(milliV, tempEx);
        textBox7.Text = tempEx.ToString();
}

然后将值milliV 传送到“Termocoppia”类中的“Calcola”方法。我用断点对其进行了调试,并确认在类中收到了该值。

“Termocoppia”类是这样的:

public  class Termocoppia
{
    public double Calcola(double milliV,  double tempEx)//here the value of milliV is still 1.111
    {  
        tempEx= milliV;//here the value of tempEx is 0???
        return tempEx;
    }
}

我希望收到与发送到广受好评的类的值完全相同的值,但我一直返回 0。如果我在“tempEx=milliV”行调试变量 tempEx,则 tempEx 的值为 0,我不明白为什么? 我很确定我在这里犯了一个初学者的错误,但我不能解决这个问题。

4

2 回答 2

2

您有两个名为“tempEx”的变量,一个字段和一个参数。您的Calcola函数修改tempEx参数(不是字段)并返回相同的值。但是调用者没有对返回的值做任何事情。我的建议是将两个这个值放入字段中tempEx

修改你的行:

thm.Calcola(milliV, tempEx);

进入:

tempEx = thm.Calcola(milliV, tempEx);

一个建议:使用编码标准来防止这种错误。参数使用 camelCasing (so tempEx),字段使用下划线 (_tempEx)。

于 2013-05-05T09:50:10.510 回答
1

您没有使用来自 Termocoppia.Calcola 的返回值。

private void OnTimerTick(object sender, EventArgs e)
{
    double milliV = Convert.ToDouble(textBox8.Text); //I have a value of 1.111
    Termocoppia thm = new Termocoppia();
    // the return value from Cacola has to be assigned to tempEx
    tempEx = thm.Calcola(milliV, tempEx);
    textBox7.Text = tempEx.ToString();
}

您不应该为 tempEx 使用相同的变量名称作为成员变量和方法参数!

于 2013-05-05T09:52:27.550 回答