我有一個系統計時器每隔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然後被轉移到方法「Calcola」之類的「Termocoppia」內。我用一個斷點調試它,並確認該值是在該類中接收的。
類「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在行「tempEx = milliV」tempEx的值是0,我不明白爲什麼?我很確定我在這裏犯了一個初學者的錯誤,但我不能正確解決這個問題。
你剛剛調試到該行或在它上面? tempEx將爲0,直到您在下一行 – Sayse 2013-05-05 09:50:18
請記住,類型'double'的參數是按值傳遞的。 'tempEx = milliV;'不會改變你的'double tempEx;',因爲它們是兩個不同的對象。作爲給參數賦值的非常簡單的規則通常不是你想要的,除了'out'和'ref'參數外。 – Dirk 2013-05-05 09:54:09
我剛剛檢查過,在「return tempEx」這一行的值是正確的(1.111),但是如果我在主窗體中檢查到私有無效OnTimerTick,它就是0.看起來我無法恢復它。 – FeliceM 2013-05-05 09:55:53