全局变量问题始终为零

时间:2014-05-18 23:10:14

标签: c#

这是我的代码:

public void calculQuita(QUITA quita, decimal total)
{ ../
    total = commission; //Affection Value of commission to Total , like this i can use it out side of my void

}

public void CalculCom(int id)
{
    ...
    decimal totalCOM = 0;
    foreach (QUITA quita in quitaList)
    {
        decimal total = 0;
        calculQuita(quita,total);
        totalCOM += total;
    }
   ....
}

运行我的程序TotalCom后的问题始终为零。我的代码中有什么问题?

3 个答案:

答案 0 :(得分:2)

calculQuita方法不会更改total的值,它会更改参数(总计)的值,该值是变量total的副本,您需要如果您想要更改它的值,请将其作为ref参数传递:

public void calculQuita(QUITA quita, ref decimal total)
{ ../
    total = commission; 

}

public void CalculCom(int id)
{
    ...
    decimal totalCOM = 0;
    foreach (QUITA quita in quitaList)
    {
        decimal total = 0;
        calculQuita(quita,ref total);
        totalCOM += total;
    }
   ....
}

进一步阅读

答案 1 :(得分:0)

您的功能calculQuita实际上正在更改总计的副本。如果您希望它更改传入的值,则必须添加ref关键字。

public void calculQuita(QUITA quita, ref decimal total)
{ ../
    total = commission; //Affection Value of commission to Total , like this i can use it out side of my void

}


public void CalculCom(int id)
{
    ...
    decimal totalCOM = 0;
    foreach (QUITA quita in quitaList)
    {
        decimal total = 0;
        calculQuita(quita, ref total);
        totalCOM += total;
    }
   ....
}

答案 2 :(得分:0)

您不应该像其他答案一样通过引用传递total。只有在您完全了解自己所做的事情时,才应使用ref。正确的方法是从commission方法返回calculQuita的值,并在适当时使用它。

public decimal calculQuita(QUITA quita)
{
    var total = 0d;
    // ...
    return commission; 
}

public void CalculCom(int id)
{
    ...
    decimal totalCOM = 0;
    foreach (QUITA quita in quitaList)
    {
        totalCOM += calculQuita(quita);
    }
   ....
}

我已经从total删除了calculQuita参数,因为它似乎没有必要 - 如果它从0以外的值开始,你仍然可以传入它。< / p>