不能隐式地将“void”转换为“十进制”

本文关键字:十进制 转换 void 不能 | 更新日期: 2023-09-27 18:32:50

futureValue = this.CalculateFutureValue(futureValue, monthlyInvestment, monthlyInterestRate, months);收到此错误,我无法弄清楚如何解决它。当我在线查找错误时,大多数答案都说将方法设为十进制而不是 void,以便它可以具有返回类型。

但是,代码的部分要求"重新设计CalculateFutureValue方法,使其成为void函数,并添加第四个参数,表示此方法返回的未来值量。

private void btnCalculate_Click(object sender, EventArgs e)
    {            
            decimal monthlyInvestment =  Convert.ToDecimal(txtMonthlyInvestment.Text);
            decimal yearlyInterestRate = Convert.ToDecimal(txtInterestRate.Text);
            int years = Convert.ToInt32(txtYears.Text);
            int months = years * 12;
            decimal monthlyInterestRate = yearlyInterestRate / 12 / 100;
            decimal futureValue = 0m;
            futureValue = this.CalculateFutureValue(futureValue, monthlyInvestment, monthlyInterestRate, months);
            txtFutureValue.Text = futureValue.ToString("c");
            txtMonthlyInvestment.Focus();            
    }

/

private void CalculateFutureValue(decimal futureValue, decimal monthlyInvestment, decimal monthlyInterestRate, int months)
    {
        for (int i = 0; i < months; i++)
        {
            futureValue = (futureValue + monthlyInvestment) * (1 + monthlyInterestRate);
        }
    }

不能隐式地将“void”转换为“十进制”

以下是

他们所说的要求的含义: 而不是这个

decimal ComputeSomething(decimal x, decimal y) {
    return x*x + y*y;
}
...
decimal result = ComputeSomething(10.234M, 20.5M);

这样做:

void ComputeSomething(decimal x, decimal y, out res) {
    res = x*x + y*y;
}
...
decimal result;
ComputeSomething(10.234M, 20.5M, out result);

请注意附加参数前面的out限定符 res 。这意味着参数是"输出",即您的方法必须在完成之前为其分配一些值。

ComputeSomething 内部对res的赋值将成为对变量 result 的赋值。

你需要通过引用传递变量:

private void CalculateFutureValue(ref decimal futureValue, decimal monthlyInvestment, decimal monthlyInterestRate, int months){ ... }

this.CalculateFutureValue(ref futureValue, monthlyInvestment, monthlyInterestRate, months);

请参阅此文档。

如果futureValue在传递给CalculateFutureValue之前没有用值初始化,则需要使用 out 关键字来代替ref