这是我的代码:
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
后的问题始终为零。我的代码中有什么问题?
答案 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>